// fstream read write file
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main ()
{
// writing to file
fstream myfile("example555.txt",ios::out|ios::app);
if (myfile.is_open())
{
// why does it collapse here: it continuously writes into the .txt
// without while it looks working good
while ( myfile.good() )
{
myfile<<"This new line has been appended to the end of the file."<<endl;
}
myfile.close();
}
else { cout << "Unable to open file for reading!"; }
// reading from file
string line;
myfile.open("example555.txt",ios::in);
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else { cout << "Unable to open file for writing!"; }
return 0;
}
// reading from file
string line;
myfile.open("example555.txt",ios::in);
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
Notice at line 33 the file is read from, using getline().
The read may fail or succeed.
Then at line 34 the line is displayed (even though we haven't checked that the getline was succcessful).
After that, the while loop condition myfile.good() is tested.
This in colloquial language, is bolting the stable door after the horse has fled.
Do this instead:
1 2 3 4 5 6 7 8 9 10 11 12 13
// reading from file
string line;
myfile.open("example555.txt",ios::in);
if (myfile.is_open())
{
while ( getline(myfile,line) )
{
cout << line << endl;
}
myfile.close();
}