Reading and Writing to Files in C++
The C++ programming language allows its users to handle and manage text and binary files through its built-in fstream class library. This includes several classes for reading and writing user-defined C++ program files. Popular file handling operations include the main file classes ifstream (input file stream), ofstream (output file stream), and fstream (both input and output). These file class libraries allow C++ users to open files, read files, create file text, and close files within the current program.

An overview of the file streams concept in C++ programming.
- ifstream (input file stream) – The ifstream class library is used to read data from existing C++ program files.
- ofstream (output file stream) – The ofstream class library is used to create and write data to existing C++ program files.
- fstream (file stream) – It is used for both read and write file handling operations to existing C++ program files.
Adding the <fstream> header file for file handling tasks.
To work with files through file handling tasks in the C++ programming language, C++ users must add the <fstream> preprocessor header file.
#include <iostream>
#include <fstream> // Add this for file handling stream operations
#include <string> // Add this for working with string data type operations
using namespace std;
File Handling: Writing data to a file (using the ofstream class).
To write data and information to C++ program files, C++ users can use the ofstream class library. With this you can open the file in write mode, and create desired data and information in it.
Basic example of writing data to a file.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// here we Create an ofstream object and open the file for operation
ofstream outFile(“samplefile.txt”);
// here it Check if the file opened successfully or not
if (outFile.is_open()) {
outFile << “Welcome to Vcanhelpsu” << endl; //here it Writing text info into the file
outFile << “We use sample file.” <<endl;
outFile << “let learn file handling in c++ program file” << endl;
outFile.close(); //here it Close the file after writing data and info
cout << “Data information added successfully in c++ program file.” << endl;
} else {
cout << “Unable to open or write data into the file.” << endl;
}
return 0;
}
Explanation of a basic method of writing data to a file.
- ofstream outFile(“samplefile.txt”) – This creates a file named “samplefile.txt” and opens it in write mode.
- outFile << “data” – This creates data and information in the file.
- outFile.close() – This closes the file after writing data to the samplefile.txt file.
Remember, if the file does not exist on your system, it will create it first. If the file already exists, the previously written file content will be automatically overwritten with the new content.
Reading from a file in file handling (using the ifstream file method).
To read data and text information from a file in a C++ program, C++ users can use the ifstream file method class. This method allows C++ users to open an existing file and read its contents in file handling operations.
Reading from a file in a basic example of file handling.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// Here we create an ifstream file object and open the file for reading from the file
ifstream inFile(“samplefile.txt”);
// Here it checks if the file opened successfully for file operations
if (inFile.is_open()) {
string line;
// Here it reads each line from the file for reading purposes
while (getline(inFile, line)) {
cout << line << endl; // Here it prints the line to the console screen
}
inFile.close(); // Here it closes the file after reading
} else {
cout << “Restrict to open file for reading purposes.” << endl;
}
return 0;
}
Explanation of reading from a file in file handling.
- ifstream inFile(“samplefile.txt”) – This creates and then opens the existing file in read mode.
- getline(inFile, line) – This file handling task reads text information from the file one line at a time into a string line. In this process, the program loops until all lines of the current file have been read.
- inFile.close() – This finally closes the file after reading the current file.
Reading and writing with the fstream library in file handling (for both input and output tasks).
C++ users can also use the fstream class library methods for file handling operations when C++ users need to simultaneously perform both file tasks: reading data and information from a file and writing new data and information to it. The fstream class is especially used when C++ users need to update or modify existing files.
Basic example of reading and writing with the fstream.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// Here we create an fstream file object and open the file in both input and output file operation modes.
fstream file(“samplefile.txt”, ios::in | ios::out | ios::app);
// here it Check if the file opened successfully or not
if (file.is_open()) {
string line;
//here it Read from the samplefile file
cout << “Reading data and information from samplefile text file.” <<endl;
while (getline(file, line)) {
cout << line << endl; //here it Print each line by line
}
// here it Move the file pointer back to the beginning for writing file text purpose
file.clear(); //here it Clear EOF flag
file.seekp(0, ios::end); // here it Move to the end for appending file mode
//here it Write to the file
file << “Here we add a new line with fstream class library.” <<endl;
file.close(); // here it Close the file after reading and writing operation purpose
cout << “Data written and updated to the samplefile text file successfully.” <<endl;
} else {
cout << “Restricted to open samplefile text file for operation.” << endl;
}
return 0;
}
Explanation of reading and writing files with the fstream.
- fstream file(“example.txt”, ios::in | ios::out | ios::app) – Opens the file in append mode (ios::app) for reading data and information from the existing file (ios::in) and writing file data (ios::out), both for file handling operations and for appending new data.
- file.clear() – Clears any EOF flags set after reading data from the existing file. This enables easy access to further operations, such as seeking and writing data information to the existing file.
- file.seekp(0, ios::end) – This write moves the file pointer to the end of the file, so that new file data can be appended instead of overwriting the existing file contents.
Multiple File Operation Modes in C++ File Handling.
When opening files in a C++ file handling operation, C++ users can indicate different file handling modes (using flags). These file operation modes control how the file is opened and which file task operations are allowed.
Types of Multiple File Operation Modes in C++.
- ios::in – Opens a file for reading in a file handling operation.
- ios::out – Opens a file for writing or creating data information in a file handling operation. If the file does not exist in the system, it first creates it, or if it exists, it truncates the file.
- ios::app – Opens a file for adding new content and information to it in a file handling operation (all write operations are appended to the end of the file).
- ios::ate – Opens a file for writing in a file handling operation and immediately moves to the end of the file.
- ios::binary – Opens the file in binary mode during file handling operations, it works in reverse for text mode.
- ios::trunc – Truncates the file to zero length if it already exists in the file system.
Example Using file handling modes in different modes.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Here it opens the file in binary mode and for writing data information only
ofstream outFile(“binary_file.bin”, ios::binary);
if (outFile.is_open()) {
int data = 1031110;
outFile.write(reinterpret_cast<char*>(&data), sizeof(data)); // Here it writes an integer data to a binary file format
outFile.close();
cout << “Data information written successfully to the binary file.” <<endl;
}
// here it Open the binary file for reading purpose only
ifstream inFile(“binary_file.bin”, ios::binary);
if (inFile.is_open()) {
int readFileData;
inFile.read(reinterpret_cast<char*>(&readFileData), sizeof(readFileData)); //here it Reading data from a binary file
cout << “Binary file Read data operation performed successfully. ” << readFileData << endl;
inFile.close();
}
return 0;
}
Explaining how to use different file handling modes.
- ios::binary – This fixes file handling so that the file is opened in binary mode only.
- outFile.write(reinterpret_cast<char*>(&data), sizeof(data)) – This creates a binary representation of integer data in a file in binary file handling.
- inFile.read(reinterpret_cast<char*>(&readData), sizeof(readData)) – This reads binary file data back into readFileData in file handling.
Error handling with file operations in file handling.
Multiple file handling modes in file handling. When working with files, C++ users must manage and handle file errors in the proper order. C++ users can apply the fail() function to check whether a file operation was successful or not.
Example with error handling in file handling.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile(“samplefile.txt”);
if (!outFile) {
cout << “Display Error – Restrict to open samplefile for writing purposes only” << endl;
return 1;
}
outFile << “Welcome to Vcanhelpsu platform” << endl;
if (outFile.fail()) {
cout << “Display Error – Writing to the samplefile task failed” << endl;
return 1;
}
outFile.close();
cout << “Samplefile Data written operation successfully to the file.” << endl;
return 0;
}
Explaining error handling in file handling.
- Here in this example, the if (!outFile) function checks whether the current file could not be opened or does not exist.
- The if (outFile.fail()) function checks if any errors were displayed while writing data and information to the current file handling file.

