Chapter 4: File and file management
• File management is an essential part of programming that allows you to store,
retrieve, and manipulate data on disk.
• In C++, file handling is performed using file streams provided by the Standard
Library, particularly through the <fstream> header.
Types of File Streams
• C++ provides three main types of file streams:
• ifstream: Input file stream used for reading from files.
• ofstream: Output file stream used for writing to files.
• fstream: A combination of both input and output file stream.
Chapter 4: File and file management
Including the Header File
To work with files in C++, include the <fstream> header at the beginning of your
program:
#include <iostream>
#include <fstream> // For file handling
#include <string> // For string manipulation
Opening and Closing Files
• You can open a file using the .open() method or by using the constructor of the file
stream classes.
• It is crucial to close the file once operations are completed using the .close()
method.
Chapter 4: File and file management
Writing to a File
• To write data to a file, use the output stream (ofstream).
• You can write strings, numbers, and other data types using the stream insertion operator
(<<).
Reading from a File
• To read data from a file, use the input stream (ifstream).
• You can read strings, numbers, and other data types using the stream extraction operator
(>>).
Error Handling
• Always check if a file opens successfully.
• You can use the .fail() method or check the stream state after attempting to open a file.
Chapter 4: File and file management
File Modes
You can specify how a file is opened by using different modes:
ios::in: Open for input operations.
ios::out: Open for output operations.
ios::app: Open for output operations and append to the end of the file.
ios::ate: Open and move to the end of the file.
ios::trunc: Truncate the file (clear its contents) if it already exists.
Chapter 4: File and file management
Random Access to Files
• Using fstream, you can perform random access operations (reading/writing at any
position in the file) using the .seekg() and .seekp() methods.
Binary Files
• You can also work with binary files using the ios::binary mode, which is essential for
storing complex data structures.
Chapter 4: File and file management
Example
1. Write a program to read a file containing integers, compute their sum, and write the
result to a new file.
2. Implement a program that creates a binary file of structures and reads the data back,
displaying the contents on the console.
3. Create a text file with a list of names and ages, and write a program to find the
average age.
4. Implement error handling in a file management program that creates, writes to, and
reads from a file.