I'm reading the man page of the open() syscall, and I noticed that there are 2 types of the function in the man page :
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
I know that in C there isn't function overloading. How can there be 2 declarations of open()? Thanks!
open
is actually declared as a variadic function. If you look in <fcntl.h>
you will see something like
extern int open (const char *pathname, int flags, ...);
So as far as the syntax is concerned, any arguments after the first two are optional.
The declarations in the man page are meant to tell you that in order for the function to actually work correctly, you should pass either no additional arguments, or one additional argument of type mode_t
. (The rest of the man page explains how to determine when to do which.)
You are quite right that there is no function overloading in C, and in fact the open
function does not actually know how many arguments you called it with. Instead* it looks at whether the O_CREAT
bit is set in the flags
argument, and if it is, it knows to expect a third argument, telling it what modes the newly created file should have. It can then obtain the value of this argument using va_arg
and friends (or in some other system-specific way). Of course, if you specify O_CREAT
but don't actually pass a third argument, or pass an argument of a different type than mode_t
, the compiler won't stop you, but something will probably go wrong when the function executes.
* There may be other conditions under which a third argument will be expected, e.g. when using the O_TMPFILE
flag, but O_CREAT
is by far the most common.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With