Thread: c++ file IO

  1. #1
    Anirban Ghosh
    Join Date
    Jan 2006
    Posts
    278

    c++ file IO

    Code:
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main()
    {
         char c;
         
         ofstream fout("O.TXT",ios::out|ios::binary);
         fout << "C++Programming";
         fout.close();
         
         ifstream fin("O.TXT",ios::in|ios::binary); 
         while( !fin.eof() )
         {
             fin.get(c);
             if( !fin.eof() )
                 cout << c;
         }
         fin.seekg(0,ios::beg);
              
         fin.get(c);
         cout << ' ' << c << endl; 
                
         fin.close();
    
         system("PAUSE");
         return 0;
    }
    The code must give the output "C++Programming C". But the output i am getting is "C++Programming g". In many cases i have seen when i have forwarded the file pointer , the characters can be well read but when the pointer is brought back the desired characters cannot be read.

    Tried on VC++ 6.0 and DEV C++ 4.9.9.0

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Because it still thinks you're at eof, so the next get call doesn't actually update c, and it's left with the last character which was successfully read.

    fin.clear(); // make the eof condition go away
    fin.seekg(0,ios::beg); // back to start

    Now I get
    $ ./a.out
    C++Programming C

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  4. Batch file programming
    By year2038bug in forum Tech Board
    Replies: 10
    Last Post: 09-05-2005, 03:30 PM
  5. File IO with .Net SDK and platform SDK
    By AtomRiot in forum Windows Programming
    Replies: 5
    Last Post: 12-14-2004, 10:18 AM