Create a file in Linux using C

前端 未结 2 1187
小鲜肉
小鲜肉 2021-02-02 11:50

I am trying to create a write only file in C on Linux (Ubuntu). This is my code:

 int fd2 = open (\"/tmp/test.svg\", O_RDWR|O_CREAT);

 if (fd2 != -1) {
   //...         


        
相关标签:
2条回答
  • Give access permissions as the third parameter:

    int fd2 = open("/tmp/test.svg", O_RDWR|O_CREAT, 0777);  // Originally 777 (see comments)
    
    if (fd2 != -1) {
        // use file descriptor
        close(fd2);
    }
    

    By doing this, all read, write and execute permissions will be given to user, group and others. Modify the 3rd parameter according to your use.

    0 讨论(0)
  • 2021-02-02 12:42

    You need the three-argument form of open() when you specify O_CREAT. When you omit the third argument, open() uses whatever value happens to be on the stack where the third argument was expected; this is seldom a coherent set of permissions (in your example, it appears that decimal 12 = octal 014 was on the stack).

    The third argument is the permissions on the file - which will be modified by the umask() value.

    int fd2 = open("/tmp/test.svg", O_RDWR | O_CREAT, S_IRUSR | S_IRGRP | S_IROTH);
    

    Note that you can create a file without write permissions (to anyone else, or any other process) while still being able to write to it from the current process. There is seldom a need to use execute bits on files created from a program - unless you are writing a compiler (and '.svg' files are not normally executables!).

    The S_xxxx flags come from <sys/stat.h> and <fcntl.h> — you can use either header to get the information (but open() itself is declared in <fcntl.h>).

    Note that the fixed file name and the absence of protective options such as O_EXCL make even the revised open() call somewhat unsafe.

    0 讨论(0)
提交回复
热议问题