0

I am using this code for simply reading from a text file but i want to put file pointer at the begining again when it reaches to the end of file.
But my code below is not working.

u can ignore extra bits of my code... like header files... :)

#include<iostream>
#include<cstdio>
#include<cstdio>
#include<cstring>
#include<fstream>
#include <string>
using namespace std;

int main(){
 char Word[20];
	ifstream file;
	string a;
	file.open("b.txt");
  while (!(file.eof())){	// run whole dic
				
	file >> Word;		// for each word
	cout << "Word Read: " << Word << endl;
	cout << "Pointer at: " << file.tellg() << endl << endl;
	if(file.tellg()==-1){
		file.seekg(0,ios::beg);
		cout << "File Pointer Now at: "<< file.tellg() << endl;
		cin >> a;
	}
 }

 return 0;
}
2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by ArkM
0

Alas, your code is wrong.

When you got the last word file.eof() is not true! Only the next file>>Word expression changes the file stream state to eof (and does not read anything). After that all operations on the file stream are suppressed until you clear() the stream.

That's right file scan loop:

while (file >> Word) {
   ...
}
if (file.eof()) {
    file.clear();
    // Now tellg/seekg work again
} else {
    // i/o error, stop processing.
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.