Is there a way to tell what mode a FILE *
was opened?
Specifically I need to tell if a file stream is writable. Either just the true/false result of whether it's writable, or the const char *
of the mode itself is good.
Not directly answer your question, but you can use freopen
FILE *freopen(const char *path, const char *mode, FILE *stream);
It opens a specified file on a specified stream, closing the stream first if it is already
open. If the stream previously had an orientation, freopen
clears it.
YES, there are ways but they are historical in nature and frowned upon by others. Also, you will need to research / test what the exact values are and then take the risk that a new release of the OS will undo your assumptions.
Anyway, given that caveat, you can test fields inside the FILE structure for specific values. The structure is in stdio.h and the fields of interest are: _flag and _file.
Write-up some characterization code and run on your system, as:
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("test1.txt", "r");
printf("(r) _flag = %04x, _file = %04x\n", fp->_flag, fp->_file);
fp = fopen("test2.txt", "a");
printf("(a) _flag = %04x, _file = %04x\n", fp->_flag, fp->_file);
fp = fopen("test3.txt", "w");
printf("(w) _flag = %04x, _file = %04x\n", fp->_flag, fp->_file);
}
You can see the _flag values associated with each type of open.
On Windows/XP, I got the following:
(r) _flag = 0001, _file = 0003
(a) _flag = 0002, _file = 0004
(w) _flag = 0002, _file = 0005
Notice, append is the same as write! The _file values appear to be the index into the _iob, where stdin is _file = 0000.
Anyway, mess around, experiment. Try writing/reading data from the files and see if _flag changes???
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