仅使用系统调用C复制文件,无限运行时间

时间:2019-03-11 03:05:31

标签: c linux

所以我正在用C语言编写一个简单的程序,但是一直停留在复制部分。该程序在命令行上使用两个文件名作为参数,然后使用系统调用将第一个文件名复制到第二个文件名。如果第二个文件存在,它将询问用户是否要覆盖,否则,它将创建该文件。但是,当用户选择覆盖时,我的程序将无限进行。

这是我的代码:

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
    int fd1, fd2;
    char buffer[1024];
    long int n;
    char c;
    int num;

    if (argc != 3) {
        printf("%d\n",argc);
        printf("Error, you need to give 2 arguments. Such that [File to copy] [File to create].\n");
        exit(1);
    }

    if (access(argv[1], F_OK) < 0) {
        printf("File %s either does not exist or cannot be accessed.\n", argv[1]);
        exit(1);
    } else {
        printf("file %s exists\n", argv[1]);
    }

    if (access(argv[2], F_OK) < 0) {
        printf("File %s does not exist, but one will be created.\n", argv[1]);
        fd2=open(argv[2],O_CREAT|O_WRONLY|O_TRUNC, 0700);
    } else {
        printf("file %s exists\n", argv[2]);
        printf("Would you like to overwrite %s? (Type 1 for yes or 0 for no)\n", argv[2]);
        scanf("%d%c", &num, &c);  // use c to capture \n
        if (num == 1) {
            fd2=open(argv[2],O_CREAT|O_WRONLY|O_TRUNC, 0700);
        } else { 
            if (num == 0) {
                printf("Ok, the file will not be copied and the program will now exit.\n");
                exit(1);
            } else {
                printf("I do not recognize this response, program will now be terminated.\n");
            }
        }
    }
    printf("step\n");
    while ((n1 = read(fd1, buffer, 1024)) > 0) {
        printf("step\n");
        if(write(fd2, buffer, n1) != n1){
            printf("step\n");
            perror("Error writing file.");
            printf("step\n");
            exit(3);
        }
        printf("stepss\n");
    }
    close(fd1);
    close(fd2);
}

printf(“ step”)用于调试,但只打印一个。这意味着程序会在while循环中冻结。我可以使用stat(),open(),read(),write(),close()和access()。任何关于错误或如何更好地解决问题的想法都将受到赞赏!

1 个答案:

答案 0 :(得分:2)

  

关于出什么问题的任何想法

您的fd1从未分配,因此read(fd1, ...)返回错误。

检查返回值readprintf("%m\n")将打印详细信息。

$ ./a.out a b
file a exists
file b exists
Would you like to overwrite b? (Type 1 for yes or 0 for no)
1
step
Bad file descriptor