UNIT 5: Working with Files
5.1 Introduction:
Classes for File Stream Operations (Introduction)
In C++, file handling is done using **file stream classes**, which allow reading from and writing to files.
These classes are part of the `<fstream>` library and handle files like streams of data, similar to how you
handle console input/output.
The main classes used for file operations are:
1. ‘ifstream` (input file stream): For reading from a file.
2. `ofstream` (output file stream): For writing to a file.
3. `fstream`: (file stream): For both reading and writing to a file.
Basic Example of File Operations
These classes make it easy to perform file input/output in C++, similar to how `cin` and `cout` work for
the console.
5.2 Opening and Closing a File
To work with files in C++, you need to **open** a file using file stream classes like `ifstream`, `ofstream`,
or `fstream`. After the file operations are done, the file should be **closed** to free system resources.
Opening a file:
- Use `.open()` to open a file.
- Files can also be opened directly when creating an object of `ifstream`, `ofstream`, or `fstream`.
Closing a file:
- Use `.close()` to close the file.
Detecting End of File (EOF)
You can detect the end of a file (EOF) using the `.eof()` function, which returns `true` when the end of
the file is reached.
File Opening Modes
When opening a file, you can specify different modes to control how the file is accessed. These modes
are combined using bitwise OR (`|`).
1. `ios::in`: Open for reading.
2. ‘ios::out`: Open for writing (erases existing content if the file exists).
3. `ios::app`: Open for appending (adds data at the end of the file without erasing it).
4. `ios::binary`: Open the file in binary mode.
5. `ios::ate`: Move the file pointer to the end of the file when opening.
6. `ios::trunc`: Truncate the file (clear the file content if it exists).
Example:
5.3 Sequential Input and Output Operations
In sequential input/output operations, data is read from or written to a file **in order**, starting from
the beginning and proceeding step by step.
Sequential Input (Reading): Data is read in the order it appears in the file.
Example (Reading from file):
Sequential Output (Writing): Data is written to the file in the order it is provided.
Example (Writing to file):
File Pointers and Their Manipulation
File pointers keep track of the current position in the file for reading or writing. You can manipulate
these pointers to move within the file.
1. `tellg()` and `tellp()`:
- Get the current position of the input(`tellg`) or output (`tellp`) file pointer.
2. `seekg()` and `seekp()`:
- Move the input (`seekg`) or output (`seekp`) file pointer to a specific position.
- You can move relative to the start (`ios::beg`), current position (`ios::cur`), or end (`ios::end`).
Example of File Pointer Manipulation
These operations let you control how you navigate through a file, enabling random access rather than
just sequential access.
5.4 Error Handling During File Operations
When working with files in C++, errors can occur, such as trying to open a non-existent file or
encountering issues while reading or writing. To handle such errors, C++ provides several ways to check
for file operation failures.
1. Checking if the File Opened Successfully
After opening a file, you can check if it was opened correctly using the `.is_open()` function.
Example:
2. File Stream Error Flags
C++ provides several error flags that can be checked after file operations:
- `fail()`: Returns `true` if an input/output operation fails (like wrong data type).
- `eof()`: Returns `true` if the end of the file is reached.
- `bad()`: Returns `true` if a critical error occurs, like a hardware failure.
- `good()`: Returns `true` if there are no errors.
Example:
3. Clearing Error Flags
If a file stream enters an error state, you can clear it using `.clear()` to reset the error flags and continue
working with the file.
Example:
Example of Complete Error Handling
This way, you can handle errors gracefully and avoid unexpected program crashes.
5.5 Updating a File: Random Access
In random access, you can directly move to any part of the file and update it without reading or writing
the entire file sequentially. This is useful for modifying specific data within large files.
File Pointers (`seekg()` for input and `seekp()` for output) are used to move to a specific location in the
file.
Example (Updating a file at a specific position):
Command Line Arguments
Command line arguments allow you to pass data to your program when you run it from the terminal or
command prompt. In C++, they are accessed via the `main()` function parameters:
- `int argc`: Number of arguments passed (including the program name).
- `char* argv[]`: An array of strings representing the arguments.
Example:
Example Usage:
If your program is compiled as `file_reader`, you can run it like this:
This will pass `"example.txt"` as the argument `argv[1]` to open and read the file.