File handling in C++ is essential for managing data outside of your program. It allows you to read from and write to files, enabling persistent storage and retrieval of information. In this guide, we’ll explore three diverse examples of file handling in C++, focusing on reading and writing files.
When you want to save information generated by your program, writing to a text file is a common use case. For instance, you might want to log user activity or save configuration settings.
#include <iostream>
#include <fstream> // Include fstream for file handling
#include <string>
int main() {
std::ofstream outFile("example.txt"); // Create an output file stream
if (outFile.is_open()) { // Check if the file is open
outFile << "This is a test file.\n"; // Write to the file
outFile << "Writing some sample text.\n";
outFile.close(); // Close the file
std::cout << "Data written to file successfully!" << std::endl;
} else {
std::cerr << "Error opening file for writing." << std::endl;
}
return 0;
}
std::ofstream
to create and write to a file named example.txt
.is_open()
method checks if the file was successfully opened before attempting to write.close()
to ensure data is flushed and resources are released.Sometimes, you need to read data from a file, such as loading user settings or reading input data for processing. This example demonstrates how to read lines from a text file.
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream inFile("example.txt"); // Create an input file stream
std::string line;
if (inFile.is_open()) { // Check if the file is open
while (getline(inFile, line)) { // Read line by line
std::cout << line << std::endl; // Print each line to the console
}
inFile.close(); // Close the file
} else {
std::cerr << "Error opening file for reading." << std::endl;
}
return 0;
}
std::ifstream
is used to read from example.txt
.getline()
function allows you to read the file line by line, making it easy to process text data in chunks.Appending data to an existing file allows you to add new information without overwriting the existing contents. This is useful for logging or adding new entries to a record.
#include <iostream>
#include <fstream>
int main() {
std::ofstream outFile("example.txt", std::ios::app); // Open in append mode
if (outFile.is_open()) { // Check if the file is open
outFile << "Appending a new line to the file.\n"; // Append text
outFile.close(); // Close the file
std::cout << "Data appended to file successfully!" << std::endl;
} else {
std::cerr << "Error opening file for appending." << std::endl;
}
return 0;
}
std::ios::app
flag is used to open the file in append mode, which means new data will be added to the end of the file.These examples of file handling in C++: reading and writing files will help you manage data efficiently in your applications. Happy coding!