Structures with File I/O
Using structures with file I/O allows you to store and retrieve complex data types—like records containing multiple fields—directly from files. This is especially useful for applications like student databases, employee records, or inventory systems.
Why Use Structures with File I/O?
- To handle grouped data (e.g., name, age, salary) as a single unit.
- To read/write entire records efficiently.
- To maintain persistent storage of structured data
Example:
struct Student {
char name[20];
int age;
};
Student s1 = {“Alice”, 20};
ofstream out(“student.dat”, ios::binary);
out.write((char*)&s1, sizeof(s1));
out.close();
Student s2;
ifstream in(“student.dat”, ios::binary);
in.read((char*)&s2, sizeof(s2));
cout << s2.name << ” ” << s2.age;
in.close();
Error Handling in File Operations
Error handling during file operations is essential to ensure data integrity and prevent unexpected behavior. The standard file stream classes (ifstream, ofstream, fstream) provide built-in member functions like fail(), eof(), bad(), and good() to monitor the state of a file stream. These functions help detect issues such as failed reads, unexpected end-of-file, or corrupted streams during runtime. Proper usage improves reliability and makes debugging file-related logic easier.
Example:
ifstream file(“data.txt”);
if(file.fail()) {
cout << “File not found!”;
}