Determine the openmode of an std file stream

Started by
5 comments, last by Zakwayda 16 years, 2 months ago
Is there any way to determine the openmode of an std::ifstream or std::ofstream?
Advertisement
What do you mean by "the openmode"? If you want to check if the file is open (for example, to see if it was successfully loaded from disk), you can use the is_open() function.
The specific information I require is whether the file is in binary mode or not. However any of the flags that are passed to the constructor could be of use, e.g. ios::binary ios::in, ios::out etc.
How do you get to a situation where you don't know whether you are in binary mode or not? That answer may help you find a solution because from what I could tell there is no quick and easy way to get this information from the file stream. I'd suggest just saving this information along with your stream. But really, I don't really see why you want to do this.

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

I am providing >> and << operators for my own types, within these operators I would like to determine whether the file is opened in binary mode or not as it will affect what I write to / read from the file i.e. :

// (SomeType is a POD)ifstream& operator >> (ifstream& input, SomeType &value){  SomeType val;  // this is what I would like to be able to do, i.e. automatic handling of binary or ascii files I know this won't compile!  if (input.openmode == ios::binary)  {    input.read((char*)&val, sizeof(SomeType));    value = val;  }  else  {    input >> value.floatMember1;    input >> value.floatMember2;  }  }...
Gah. Don't do that. Operator << and >> on standard stream objects are specifically formated insertion and extraction operators. Reading or writing binary values from the stream violates the intended interface for those operators. If you really feel the need to use << and >> for binary I/O, then create a wrapper for the binary stream so that use of the binary I/O would be dependent on type.
You might also look into the Boost Serialization library. By making your serialization function a function template parameterized by archive type, you can make your code do the Right Thing automatically depending on whether the archive is binary or text-based.

This topic is closed to new replies.

Advertisement