7

I am new to C++. I have simple question to ask you that what is the difference between std::fstream::X and std::ios::X open file mode in C++ ?

Where x can be in, out, ate, trunk, ate ?

Here is more example:

fs.open(filename.c_str(), std::fstream::in | std::fstream::out | std::fstream::app); 

vs

fs.open(filename.c_str(), std::ios::in | std::ios::out | std::ios::app); 

what is the difference between these two ?

Please don't answer in a complicated manner since I am beginner in C++.

4
  • It's inheritance working there Commented Jan 11, 2016 at 13:55
  • what does mean this ? Commented Jan 11, 2016 at 13:56
  • ios is base class of fstream Commented Jan 11, 2016 at 13:57
  • so what do it ? can so explain in more detail please.. with an possible example Commented Jan 11, 2016 at 13:58

3 Answers 3

3

Quoting Input/Output in File

class: default mode parameter

ofstream: ios::out

ifstream: ios::in

fstream: ios::in | ios::out

For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even if a mode that does not include them is passed as second argument to the open() member function.

std::fstream is inherited from std::ios, according to this page

When reading from a file, I prefer to use std::ifstream::in flag, because it could be a good programming practice to let a programming interface know what you are going to use it for.

Sign up to request clarification or add additional context in comments.

2 Comments

what means inherited ?
@Aryan It means the inheritance in C++, one good resource is here
2

There's no difference. std::fstream::X is inherited from std::ios, so it's the same value as std::ios::X.

Comments

1

Alice has a son, Bob. They both have the same hair color -- brown, let's say. Now, someone asks you: "What's their family's hair color?" You could say Alice's or Bob's: it's the same.

Can you see the point? Although the color is the same, Bob has inherited her mother's. It's the same for std::ios::in and std::fstream::in -- it's the same value, since they have an inheritance relation, but it's their "own" value because they are not the same type (likewise, Alice and Bob are not the same person).

Comments