This code will read a file and display its content to the output stream (console), while being on the lookout for errors.
1. #include <iostream>
2. #include <fstream>
3. using namespace std;
4.
5. void FileState(ifstream &in);
6.
7. int main(int argc, char *argv[])
8. {
9. ifstream inFile("C:\\NEWS.txt");
10.
11. if(!inFile)
12. {
13. cout << "Cannot open input file.\n";
14. return 1;
15. }
16.
17. char currChar;
18. while(inFile.get(currChar))
19. {
20. cout << currChar;
21. FileState(inFile);
22. }
23.
24. FileState(inFile);
25. inFile.close();
26. system("PAUSE");
27. return 0;
28. }
29.
30. void FileState(ifstream &inFile)
31. {
32. ios::iostate currState;
33.
34. currState = inFile.rdstate();
35.
36. if(currState & ios::eofbit)
37. {
38. cout << "End of File\n";
39. }
40. else if(currState & ios::failbit)
41. {
42. // Recoverable I/O error
43. cout << "Reading Failure\n";
44. }
45. else if(currState & ios::badbit)
46. {
47. // Unrecoverable I/O error
48. cout << "Stream Corrupted\n";
49. }
50. }