Hi,

I wish to read an input file 5 times. I am able to read it once but when i try to read it second time i am unable to do that because the file pointer is stuck at EOF.
Can anyone suggest a small sample code of how to do that?

Thanks and Regards

Dani AI

Generated

The stream is at EOF because the stream’s EOF/fail flags are set after the first complete read. ’ close/clear/reopen approach will work; ’s “SeekTobegin” idea is the right general direction but that exact name is MFC/CFile-specific, and correctly points out that using the output pointer (seekp) is the wrong choice for input streams.

For standard C++ file input there are two common, reliable choices:

  • Reset the stream state and move the input (get) pointer back to the start, then read again. In other words, clear the stream’s error flags and use the input seek operation to jump to the beginning — this avoids repeating an open/close and is efficient for repeated passes. See the reference for stream state reset and repositioning: std::basic_ios::clear and std::basic_istream::seekg.
  • Close and re-open the file for each pass. Simpler and foolproof, but has higher OS overhead.

If you need many passes and the file is small enough, read it once into memory (a string or vector of lines) and iterate that in memory to avoid repeated disk I/O. For very large data sets consider platform mmap solutions. Always check stream state after I/O and don’t use the output-positioning API for input streams.

Recommended Answers

All 3 Replies

fin.close( );
fin.clear( );
fin.open( "yourfile.txt);

Hope you have tried... SeekTobegin()

fin.seekp(ios::begin)
fin.clear();

>>Hope you have tried... SeekTobegin()
That is only for MFC CFile class. Not available to anything else.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.