Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the file-mode from the FILE struct?

Tags:

c++

c

file-io

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.

like image 232
Evianil Avatar asked Sep 29 '22 06:09

Evianil


1 Answers

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.

like image 147
R.. GitHub STOP HELPING ICE Avatar answered Nov 15 '22 07:11

R.. GitHub STOP HELPING ICE