How to read a file again


How do i read this file again after it reached the end.
The last statement doesn't take the file back to the begining.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char* argv[])
{
	ifstream file("text.txt");
	char ch;
	
	file >> ch;
	cout << ch << endl;

	file.seekg(ios::beg);
	file >> ch;
	cout << ch << endl;

	while(file.get(ch))
		cout << ch;

	file.seekg(ios::beg);  // should go back to the begining
	file >> ch;
	cout << "\n" << ch << endl;

	return 0;
}
after the loop of lines 17-18 the stream won't be good as file.get would have failed.
You can set the stream state to good using file.clear();
http://www.cplusplus.com/reference/iostream/ios/clear/
Topic archived. No new replies allowed.