Search code examples
c++fileio

What's the difference betwen once and double opening of "fstream" in c++ (In the fst case input doesn't working)?


I have the file "input file.txt":

Hello

I have the following code:

fstream ff;
ff.open("input file.txt");
ff.open("input file.txt", ios::in);
for (string s; ff >> s; cout << s)
    ;

which outputs:

<empty>

and the second code (there is one change):

fstream ff;
//ff.open("input file.txt");
ff.open("input file.txt", ios::in);
for (string s; ff >> s; cout << s)
    ;

which outputs:

Hello

The question is why?


Solution

  • If the stream is already associated with a file (i.e., it is already open), calling this function (open()) fails: http://www.cplusplus.com/reference/fstream/fstream/open/

    So your second call fails. Hence the result you get.