This may sound like a strange question, but am I safe in defining operator<<
or operator>>
for a FILE
object, or would I be violating potential clauses in the C or C++ standards, or can it possibly cause other issues?
(Yes, I do know about C++ I/O streams. I'm not asking if this is a good idea. I'm asking if it's allowed.)
Example:
#include <stdio.h>
FILE &operator>>(FILE &file, int &d)
{
if (fread(&d, sizeof(d), 1, &file) != 1)
{ throw "I/O error"; }
return file;
}
int main()
{
int x;
FILE *file = fopen("File.bin", "rb");
*file >> x;
fclose(file);
return x;
}
Ignoring, for the moment, the question of whether this is a good idea (but it's not), it's open to question whether this is truly allowed.
The C++ standard defines all the relevant headers and functions--<cstdio>
is covered in §27.9.2. If you really wanted to use it, <stdio.h>
is even part of the C++ standard (§D.5), though it's officially deprecated.
That would tend to indicate that it's allowed. The wording from the C standard (§7.19.1/2) is:
FILE
which is an object type capable of recording all the information needed to control a stream, including its file position indicator, a pointer to its associated buffer (if any), an error indicator that records whether a read/write error has occurred, and an end-of-file indicator that records whether the end of the file has been reached;
The question would be whether a FILE
is really required to represent that type directly, or could (for example) be typedef
d to void
, so (for example) fopen
actually returns a void *
. The internals of the library that use it would cast it to the proper type, but to the outside world (i.e., your program) it's completely opaque. In particular, if it is a void *
, you can't dereference it, not even to just get a reference instead of a pointer.
I'd guess that's mostly theoretical though. I think in general, assuming that FILE
is a unique type on which you can do overloading is fairly safe. You shouldn't assume anything about the internals of what it points at, but you're fairly safe assuming you can dereference it to get a reference instead of a pointer (and fairly safe assuming that the overload will be differentiated from overloads on other types such as integers).
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