Evianil
Evianil

Reputation: 53

Getting the file-mode from the FILE struct?

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.

Upvotes: 5

Views: 1431

Answers (2)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215517

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.

Upvotes: 5

Ed Heal
Ed Heal

Reputation: 60027

Assuming Linux/Unix:

See fstat(), to get the details of file permissions.

To get the file descriptor us fileno() for that function

Upvotes: -1

Related Questions