What's the connection between flags and mode in open file function in C

一个人想着一个人 提交于 2020-02-23 04:00:12

问题


I'm a beginner in C, have a question about the flags and mode paramaters in open file function in C so C's open function is :

int open(char *filename, int flags, mode_t mode);

and some macros for the flags are:

  • O_RDONLY: Reading only
  • O_WRONLY: Writing only
  • O_RDWR: Reading and writing

and the mode bit is something like:

What I don't understand is, let say we have a open function as:

fd = Open("foo.txt", O_RDONLY, S_IWOTH);

so O_RDONLY specifies that we can only read the file, but S_IWOTH specifies that anyone can write this file, isn't that they contradict to each other?


回答1:


The flags decide the properties to be applied during opening of this file at this time (let's call this the "session") - this affects what you can do with the file while it's open (or, more correctly, what you can do with the file descriptor).

The mode decide the properties of the file should it be created as part of the opening process - this affects how anyone can open the file in future.

Your specific example (albeit with the correct open rather than Open):

fd = open("foo.txt", O_RDONLY, S_IWOTH);

is not really relevant since the file won't be created without the O_CREAT flag(a).

However, had you supplied O_CREAT, it's perfectly acceptable to create the file allowing anyone to write to it, but have it opened for this session in read-only mode.


(a) Some systems have other flags which may create the file under some circumstances. For example, Linux has the O_TMPFILE flag.



来源:https://stackoverflow.com/questions/53807679/whats-the-connection-between-flags-and-mode-in-open-file-function-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!