C++ provides a flexible way to work with files using input/output streams. These streams can be categorized into two main types: sequential access files and random access files.
Sequential Access Files
In sequential access files, data is read or written sequentially, one record after another. You can't directly access a specific record without reading all the preceding records.
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Writing to a text file
ofstream outfile("text.txt");
outfile << "Hello, world!" << endl;
outfile.close();
// Reading from a text file
ifstream infile("text.txt");
string line;
while (getline(infile, line)) {
cout << line << endl;
}
infile.close();
return 0;
}
Random Access Files
In random access files, you can directly access any part of the file, allowing for efficient reading and writing of specific data.
Key Functions for Random Access:
seekg(): Sets the position of the get pointer.
seekp(): Sets the position of the put pointer.
tellg(): Returns the current position of the get pointer.
tellp(): Returns the current position of the put pointer.
Error Handling:
fail(): Returns true if the last input/output operation failed.
bad(): Returns true if a system-level error occurred.
eof(): Returns true if the end-of-file has been reached.
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Writing to a binary file
ofstream outfile("binary.bin", ios::binary);
int data = 42;
outfile.write(reinterpret_cast<char*>(&data), sizeof(data));
outfile.close();
// Reading from a binary file
ifstream infile("binary.bin", ios::binary);
int read_data;
infile.seekg(0); // Seek to the beginning of the file
infile.read(reinterpret_cast<char*>(&read_data), sizeof(read_data));
cout << "Read data: " << read_data << endl;
infile.close();
return 0;
}
Explanation of the Code:
reinterpret_cast<char*>(&data): This casts the address of the data variable to a char* pointer. This is necessary because write() and read functions expect a pointer to a character array.
sizeof(data): This calculates the size of the data variable in bytes.
seekg(0): This sets the get pointer to the beginning of the file.
By understanding the concepts of sequential and random access files, you can effectively work with different types of data in your C++ programs.
Comments