简体   繁体   中英

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())
{    
    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM