Reputation: 2146
While debugging someone else's code I came across an interaction between C++'s fstream
object, input via the stream operator and ios::app
which I was not previously aware of.
Assume file.txt
exists and contains textual data. The fstream
in its original context was long lived and served for both input and output. The following code does not work as expected (provides no output from the file), error handling code has been omitted:
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream f("file.txt", ios::app);
string in;
f >> in;
cout << in << endl;
f.close();
return 0;
}
Changing the file open statement to the following resolves the issue:
fstream f("file.txt");
Is this expected behaviour? Should it not be possible to open an fstream
object with ios::app and expect input via the stream operators to behave correctly?
Compiled with g++ 4.6.3 on 64-bit Linux and mingw-g++ 4.4.1 on 32-bit Windows 7
Upvotes: 0
Views: 330
Reputation: 409176
If you check the std::fstream
constructor you will note that the default argument is a bitfield of the flags ios_base::in
and ios_base::out
. By supplying only ios_base::app
as the flag you make the file append-only. If you want both input and append, then you have to use e.g. ios::in | ios::app
.
Upvotes: 3