使用系统调用创建新文件

时间:2017-04-03 06:20:14

标签: c posix system-calls

我尝试使用systemcalls来创建新文件/覆盖现有文件,但由于某种原因,我有两个问题:

1
。当我第一次运行程序时,它以值0退出,所以它似乎成功创建了文件,但我在项目目录中看不到任何内容。
然后当我第二次运行程序时,文件被创建,但屏幕上会显示一条错误消息。


2.同样在程序第一次迭代之后,我无法在主函数的末尾看到prinf消息。

感谢您的帮助。

    int readFileDesc = 0, writeFiledesc = 0;
    int sourceFile = 1, destFile = 2, bufferSize = 3, isOverwrite;

    if (argc != 4 && argc != 5) {
        printf("Invalid number of arguments\n");
        printf("Usage:\n");
        printf("     ex1 [-f] SOURCE DEST BUFFER_SIZE");
        exit(EXIT_FAILURE);
    }

    //Checking if -f [OP] is activated.
    isOverwrite = (strcmp(argv[1], "-f") == 0);

    if (isOverwrite) {
        sourceFile++;
        destFile++;
        bufferSize++;
    }

    //Opening the source file
    readFileDesc = open(argv[sourceFile], O_RDONLY);
    if (readFileDesc < 0) {
        perror("Unable to open source file for reading: ");
        exit(EXIT_FAILURE);
    }

    //opening the destination file

    if (!isOverwrite) {
        //Case we dont have the -f [op] so we create the file.
        writeFiledesc = open(argv[destFile],
                O_CREAT | O_EXCL | O_WRONLY ,
                S_IRUSR | S_IWUSR);
        if (writeFiledesc < 0) {
            perror("Unable to open destination file for reading: ");
            exit(EXIT_FAILURE);
        }
    } else {
        //Case we have the -f [op] so we override existing file.
        writeFiledesc = open(argv[destFile], O_RDONLY | O_WRONLY | O_TRUNC);
        if (writeFiledesc < 0) {
            perror("Unable to open destination file for writing: ");
            exit(EXIT_FAILURE);
        }
    }

    //Assume the buffersize is legal.
    bufferSize = atoi(argv[bufferSize]);
    char data[bufferSize];
    int nread, nwrite;
    while ((nread = read(readFileDesc, data, bufferSize)) > 0) {
        if ((nwrite = write(writeFiledesc, data, nread)) != nread) {
            printf("write problem: ");
        }
    }
// cant see this!
    printf("File %s was copied to %s" , argv[sourceFile] , argv[destFile]);
    //handling errors
    close(sourceFile);
    close(destFile);

        return EXIT_SUCCESS;
    }

1 个答案:

答案 0 :(得分:0)

这是错误的:

O_RDONLY

同时使用O_WRONLYO_RDWR是错误的。您需要使用#include <sys/stat.h> #include <fcntl.h> int open(const char *path, int oflag, ...);

the POSIX standard for open()

  

<强>概要

oflag
     

...

     

oflag的值由包含按位的OR标志构成   来自以下列表,定义于。 申请人应   准确指定前五个值之一(文件访问模式)   低于read():      

了O_EXEC

     

仅供执行(非目录文件)。如果将此标志应用于目录,则结果未指定。

     

O_RDONLY

     

仅供阅读。

     

O_RDWR

     

开放阅读和写作。如果将此标志应用于FIFO,则结果未定义。

     

O_SEARCH

     

仅打开搜索目录。如果将此标志应用于非目录文件,则结果未指定。

     

O_WRONLY

     

仅供写作。

     

可以使用以下任意组合:

     

...

此外,write()ssize_t返回int,而不是$scope.$apply(function(){ $scope.isLoading = false; });

相关问题