tags:

views:

63

answers:

2

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();
+3  A: 

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);
KennyTM
@Kenny Thank you very much but I edited the code as shown in the post. Now I am getting same garbage value.
brett
@brett: Not reproducible. I got `world` on the screen. (Call `seekg(0)` *only after* you have written everything.)
KennyTM
A: 

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.

jon hanson