Thread: c++ file IO

  1. #1
    Anirban Ghosh
    Join Date
    Jan 2006

    c++ file IO

    #include <iostream>
    #include <fstream>
    using namespace std;
    int main()
         char c;
         ofstream fout("O.TXT",ios::out|ios::binary);
         fout << "C++Programming";
         ifstream fin("O.TXT",ios::in|ios::binary); 
         while( !fin.eof() )
             if( !fin.eof() )
                 cout << c;
         cout << ' ' << c << endl; 
         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++

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    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