1. Introduction:
File processing is a crucial part of programming that allows data to be stored permanently on disk for
later use. Unlike variables, which are temporary and stored in RAM, files allow persistent storage. In C+
+, file processing is handled through streams, which are objects used to perform input/output
operations.
Key Points:
1. Files store data permanently.
2. Streams abstract the data transfer between a program and storage devices.
3. Two main types of file processing:
Sequential File Processing: Read/write data in order, from start to end.
Random-Access File Processing: Access any part of the file directly.
2. Files and Streams
2.1 File Types
1. Text Files: Store data as human-readable characters.
2. Binary Files: Store data in binary format (not human-readable), useful for exact storage of objects.
2.2 Streams in C++
C++ uses stream classes from `<fstream>` for file operations:
1. `ifstream` → Input file stream (read files)
2. `ofstream` → Output file stream (write files)
3. `fstream` → General file stream (read and write)
Example:
, Program Statement
Write a program to create and open a file named example.txt, write the text “Hello, File Processing!”
into the file, and then close the file. If the file cannot be opened, display an error message on the
screen.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream outFile("example.txt"); // Create and open file
if (outFile.is_open()) {
outFile << "Hello, File Processing!" << endl; // Write to file
outFile.close(); // Close the file
} else {
cout << "Unable to open file." << endl; // Error message
}
return 0;
}
Explanation:
1. ofstream outFile("example.txt"); → Creates or overwrites `example.txt`.
2. outFile << "..." → Writes data to file.
3. outFile.close()→ Closes the file to free resources.
3. Sequential File Processing
Sequential file processing means reading or writing data **in order**. It is like reading a book from page
1 to the end.
3.1 Creating a Sequential File