int open(const char *path, int oflag, ... );
The problem is that its arguments aren't fixed,
is there a way to wrap around it?
int my_open(const char *path, int oflag, ... ){
}
int open(const char *path, int oflag, ... );
The problem is that its arguments aren't fixed,
is there a way to wrap around it?
int my_open(const char *path, int oflag, ... ){
}
To wrap a variadic function in the general case, it needs to have a variant that takes the va_list
as an argument (this is what the vprintf
family of functions are for, for instance).
However, open
only ever has two or three arguments, so it can be wrapped by conditionally reading the third argument, but unconditionally passing three arguments to the real open
:
#ifndef O_TMPFILE
# define O_TMPFILE 0
#endif
int my_open(const char *pathname, int flags, ...)
{
mode_t mode = 0;
if (flags & (O_CREAT|O_TMPFILE))
{
va_list ap;
va_start(ap, flags);
mode = va_arg(ap, mode_t);
va_end(ap);
}
// ... do what you need to do here ...
return open(pathname, flags, mode);
}
This works because extra arguments to a variadic function are harmless; they'll just get ignored. However, you will need to update the if
condition every time the operating systems you care about add new flags that require the third parameter. The original version of this answer didn't account for O_TMPFILE
, for instance. (It's not safe to read the third parameter unconditionally; if the compiler ever managed to notice that you were reading a parameter that wasn't passed, it would be nasal demons time.)
There is no open() function defined in the C language standard. Although open() by POSIX
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
As Etienne asked - "What are you trying to do"
Early versions of the open()
function were described with an optional argument, but modern POSIX defines it as a variadic function with , ...
in its prototype.
Wrapping a variadic function with another is generally difficult, which is why the standard has vfprintf()
and friends. But since the valid variations for open()
are quite simple, with the presence or absence of the third argument determined by the value of the second, you can use a simpler approach.
Write your own my_open()
function that uses <stdarg.h>
to access the optional third argument. Depending the value of oflag
, do either
return open(path, oflag);
or
return open(path, oflag, third_arg);
you can't wrap open() without using inline assembly or SWIG (a library for calling C)
EDIT: wow, holy downvotes folks. As the OP's post has now been entirely rewritten to clarify what his question was, I suggest another SO post which has a good discussion: Passing variable number of arguments around