954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

i m unable to move file pointer to the begining of file ???

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;
}
defender_
Newbie Poster
11 posts since May 2009
Reputation Points: 10
Solved Threads: 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.
}
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You