Using the open() system call

前端 未结 5 1701
说谎
说谎 2020-12-17 17:11

I\'m writing a program that writes output to a file. If this file doesn\'t exist, I want to create it.

Currently, I\'m using the following flags when calling open: O

相关标签:
5条回答
  • 2020-12-17 17:42

    Just use the optional third argument to open:

    int open(const char* pathname, int flags, mode_t mode);
    

    so like this:

    open("blahblah", O_CREAT | O_WRONLY, S_IRUSR | S_IWUSER | S_IRGRP | S_IROTH);
    

    See man open(2).

    0 讨论(0)
  • 2020-12-17 17:43

    You probably need the third argument. For example:

    open('path',O_WRONLY|O_CREAT,0640);
    
    0 讨论(0)
  • 2020-12-17 17:47

    From the manual:

    O_CREAT

    If the file exists, this flag has no effect except as noted under O_EXCL below. Otherwise, the file shall be created; the user ID of the file shall be set to the effective user ID of the process; the group ID of the file shall be set to the group ID of the file's parent directory or to the effective group ID of the process; and the access permission bits (see ) of the file mode shall be set to the value of the third argument taken as type mode_t modified as follows: a bitwise AND is performed on the file-mode bits and the corresponding bits in the complement of the process' file mode creation mask. Thus, all bits in the file mode whose corresponding bit in the file mode creation mask is set are cleared. When bits other than the file permission bits are set, the effect is unspecified. The third argument does not affect whether the file is open for reading, writing, or for both. Implementations shall provide a way to initialize the file's group ID to the group ID of the parent directory. Implementations may, but need not, provide an implementation-defined way to initialize the file's group ID to the effective group ID of the calling process.

    So it seems you need to pass a third argument specifying the desired file permissions.

    0 讨论(0)
  • 2020-12-17 17:51

    On Linux there's a third argument you can use to pass permissions. S_IWUSR should be the flag to give you write permissions, but in practice you'll probably want to use more flags than just that one (bitwise or'd together). Check the manpage for a list of the permission flags.

    0 讨论(0)
  • 2020-12-17 17:54

    Note that under POSIX (Unix, Linux, MacOS, etc) you can open and create a file with any permissions you choose, including 0 (no permission for anyone), and yet still write to the file if opened for writing.

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