Garbage values when writing and reading to a text file
Can Some one help me the problem with this code? I am getting bunch of garbage value !
fstream fs("hello.txt");
if(fs.is_open开发者_Python百科())
{
string s = "hello";
string line;
fs << s;
while(getline(fs,line))
{
cout << line;
}
cin.get();
}
fs.close();
Thank you very much but when I try to do this I am getting same garbage. I am trying to rewrite the first hello with world and trying to print that line
fstream fs("hello.txt");
if(fs.is_open())
{
string s = "hello";
string line;
fs << s << endl;
fs.seekg(0);
fs << "world" << endl;
fs.seekg(0);
while(getline(fs,line))
{
cout<<line;
}
cin.get();
}
fs.close();
The cursor of fs
is at the end of file after you fs << s
(this is required to append data to the file properly).
Try to call fs.seekg(0);
to move the cursor back to the beginning.
Also, you may need to supply the fstream::trunc
or fstream::app
flag when constructing fs
.
fstream fs("hello.txt", fstream::in | fstream::out | fstream::trunc);
If hello.txt is empty prior to running the program then it seems to work for me. If the file contains more than 6 or 7 characters then your hello world code will overwrite the first 6/7 chars with "world" followed by the line terminator (which might be 1 or 2 chars depending on the platform). The reminder of the file won't be overwritten and will be subsequently printed by your getline loop.
精彩评论