When I man 2 open, I got below:
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
int creat(const char *pathname, mode_t mode);
int openat(int dirfd, const char *pathname, int flags);
int openat(int dirfd, const char *pathname, int flags, mode_t mode);
It is very like function overload. But it is said that C does not support function overload at all. So what is the magic here?
These functions aren't really multiple functions, just a single variadic function, accepting variadic arguments, which allows an "overload" in the sense that you can call them with or without their final argument. For example, the actual declaration of openat
on my system (omitting attribute tags and the like) is:
extern int openat (int __fd, const char *__file, int __oflag, ...);
That final ...
means it can accept additional arguments via stdarg.h
's variable arguments APIs (va_start
/va_arg
/va_end
).
To see the actual definition of these functions, run this command:
echo "#include <stdio.h>" | gcc -E - | grep -C5 "open"
This will preprocess the one line of source code and tell you what's happening under the hood.
The result should be something like this:
int open(const char *, int, ...);
This is a typical varargs function like printf
, but you as the programmer are supposed to only ever pass a single argument of type mode_t
, or none at all.
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