I have a piece of C code, a function to be specific, which operates on a FILE*
.
Depending on which mode the FILE*
was opened with there are certain things I can and cannot do.
Is there any way I can obtain the mode the FILE*
was opened with?
That FILE*
is all the info I can rely on, because it is created somewhere else in the program and the actual file-name is long lost before it reaches my function, and this I cannot influence.
I would prefer a portable solution.
Edit: I'm not interested in file-restrictions specifying which users can do what with the file. That is mostly irrelevant as it is dealt with upon file-opening. For this bit of code I only care about the open-mode.
On POSIX (and sufficiently similar) systems, fcntl(fileno(f), F_GETFL)
will return the mode/flags for the open file in the form that would be passed to open
(not fopen
). To check whether it was opened read-only, read-write, or write-only, you can do something like:
int mode = fcntl(fileno(f), F_GETFL);
switch (mode & O_ACCMODE) {
case O_RDONLY: ...
case O_WRONLY: ...
case O_RDWR: ...
}
You can also check for flags like O_APPEND
, etc.
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