reading a file multiple times

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mahmoodn
    New Member
    • May 2009
    • 77

    reading a file multiple times

    I'm opening a file and reading to the end of it. Then I want to go back to the beginning to read some other data. I wrote this code:
    Code:
    	ifstream fin2( "dictionary.txt" );
    	if ( !fin2.is_open() ) {
    		std::cerr << "failed to open dictionary.txt\n";
    		exit( 1 );
    	}
    
    	for ( ..... ) {
    		while(!fin2.eof()) {
    			getline( fin2, line );
    			.....
    		}
    		fin2.close();
    		fin2.open("dictionary.txt");
            }
    Tracing the code is: for the first time, "while" loop is done completely. Then I close the file and open it again. in the next loop ("for" loop), the program does not enter the "while" loop. That means it is stuck at the end of the file. Any idea? thanks,
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Instead of calling .close then .open call .seekg

    Comment

    • mahmoodn
      New Member
      • May 2009
      • 77

      #3
      yes, instead of
      Code:
      fin2.close();
      fin2.open("dictionary.txt");
      I have to use:
      Code:
      [B]fin2.clear();
      fin2.seekg(0, ios::beg);[/B]
      Thanks :)

      Comment

      Working...