Determine the openmode of an std file stream

This topic is 3882 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Is there any way to determine the openmode of an std::ifstream or std::ofstream?

Share on other sites
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.

Share on other sites
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.

Share on other sites
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.

Share on other sites
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;  }  }...

Share on other sites
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.

Share on other sites
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.

1. 1
2. 2
3. 3
Rutin
19
4. 4
5. 5

• 10
• 21
• 9
• 31
• 16
• Forum Statistics

• Total Topics
632618
• Total Posts
3007464

×