C++ File Input/Output

This note covers the basics of C++ file input/output using the <fstream> header.

Opening Files

To work with files, you need to create file stream objects. There are three main classes:

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:

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
}

Reading from Files

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

Writing to Files

Use the << operator to write data to a file, similar to writing to std::cout:

outputFile << "Hello, file!" << std::endl;

Closing Files

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.

Example

#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;
}