Q:

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

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?

A:

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.

