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. }
Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology.
Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach