开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜