This note covers the basics of C++ file input/output using the
<fstream>
header.
To work with files, you need to create file stream objects. There are three main classes:
std::ifstream
: For input (reading) from a file.std::ofstream
: For output (writing) to a file.std::fstream
: For both input and output.To open a file, you use the open()
method:
std::ifstream inputFile; inputFile.open("my_file.txt"); // Open for reading std::ofstream outputFile; outputFile.open("output.txt"); // Open for writing std::fstream inOutFile; inOutFile.open("data.txt", std::ios::in | std::ios::out); // Open for both
You can also specify the open mode (e.g., appending, binary) as the second argument to open()
. Common modes include:
std::ios::in
: Input mode (default for ifstream
).std::ios::out
: Output mode (default for ofstream
). Creates the file or overwrites if it existsstd::ios::app
: Append mode.std::ios::binary
: Binary mode.It's crucial to check if the file opened successfully:
if (!inputFile.is_open()) { std::cerr << "Error opening file!" << std::endl; return 1; // Indicate an error }
Use the >>
operator to read data from a file, similar to reading from std::cin
:
int number; inputFile >> number; std::string line; std::getline(inputFile, line); // Read a whole line
Use the <<
operator to write data to a file, similar to writing to std::cout
:
outputFile << "Hello, file!" << std::endl;
It's essential to close files when you're finished with them to release resources:
inputFile.close(); outputFile.close(); inOutFile.close();
Files are often automatically closed when their corresponding stream objects go out of scope (RAII - Resource Acquisition Is Initialization), but it is still good practice to close them explicitly.
#include <iostream> #include <fstream> #include <string> int main() { std::ofstream outputFile("output.txt"); if (outputFile.is_open()) { outputFile << "This is a line in the file.\n"; outputFile.close(); } std::ifstream inputFile("output.txt"); if (inputFile.is_open()) { std::string line; while (std::getline(inputFile, line)) { std::cout << line << std::endl; } inputFile.close(); } return 0; }