A simple question:
How do I check the access mode of an already opened file pointer?
So say a function is passed an already opened FILE pointer:
Warning: this answer is specific to Visual Studio 2010.
The stdio.h file that comes with Visual Studio 2010 defines the FILE type like this:
struct _iobuf {
char *_ptr;
int _cnt;
char *_base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char *_tmpfname;
};
typedef struct _iobuf FILE;
When fopening a file with the "rb" mode, it gets the value of 0x00000001.
In the fopen function, some of the flags you're interesed in can be mapped as this:
r _IOREAD
w _IOWRT
a _IOWRT
+ _IORW
These constants are defined in stdio.h:
#define _IOREAD 0x0001
#define _IOWRT 0x0002
#define _IORW 0x0080
The underlying file descriptor contains more info, I haven't dug further yet.
There is no standard way to achieve that.
On Linux (and possibly all UNIX systems) you could use fcntl
to get the access mode of the file:
int get_file_status(FILE* f) {
int fd = fileno(f);
return fcntl(fd, F_GETFL);
}
Note that the returned value is an integer as combination of flags like O_RDONLY
or O_RDWR
, not the "r"
or "w+"
strings. See http://pubs.opengroup.org/onlinepubs/007908799/xsh/open.html for some of these flags.
Not sure about Windows, see On Windows/mingw, what is the equivalent of `fcntl(fd, F_GETFL) | O_ACCMODE`?.