University of Leeds

Basic File Operations

Introduction

Working with files is a common requirement when writing computer programs. Programs may be required to read in settings or data that is stored in text files. Additionally, programs may process some input data and then write the output data to text files. These text files are often then processed using other software such as graphing and/or databases.

We will first look at some basic file input and output file operations using the C++ fstream library.

Output

The example code below shows how to write to a file.

main.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <fstream>
#include <iostream>

int main() {
  // create an output file stream
  std::ofstream output;
  // use it to open a file named 'output.txt'
  output.open("output.txt");
  // check if the file is not open
  if (!output.is_open()) {
    // print error message and quit if a problem occurred
    std::cerr << "Error creating file!\n";
    exit(1);
  }
  // print to the file and then close the stream
  output << "Hello, File!" << std::endl;
  output.close();

  // Re-open file in 'append' mode so we can write more to it
  // if we do not open in 'append' mode, the original contents
  // will be written over
  output.open("output.txt", std::fstream::app);
  output << "Appending a line!" << std::endl;
  // always remember to close a filestream when done
  output.close();
}

The first thing to do when working with files is to create a stream. In this example we create an output file stream using the ofstream class. We can then use the open() method to specify which files to write to. If the file does not exist, it will be created. If it does exist, the existing file will be over-written.

It is a good idea to check whether the file has been opened correctly using the is_open() method. It is has not been opened correctly, a message is printed to cerr and the program exits.

If it has been opened without errors, we can simply write data to the stream using the << operator. When you have finished writing to a file, it is important to remember to close it using the close() method.

As mentioned earlier, if an existing file is opened, the contents of the file will be over-written. If you wish to open a file and append data to end of the file i.e. add data to the end of the file and keep any existing dat, you can specify the mode to be std::fstream::app when opening the output stream.

Running the example above will result in a file output.txt being created with the contents

Hello, File!
Appending a line!

Input

The example below demonstrates how to read in data from a file.

main.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <fstream>
#include <iostream>
#include <string>

int main() {
  // create an input file stream
  std::ifstream input;
  // use it to open a file named 'input.txt'
  input.open("input.txt");
  // check if the file is not open
  if (!input.is_open()) {
    // print error message and quit if a problem occurred
    std::cerr << "Error! No input file found!\n";
    exit(1);
  }
  // create a string to hold the file contents
  std::string input_string;
  input >> input_string;
  // print to terminal
  std::cout << "Read \"" << input_string << "\" from file." << std::endl;
  // convert string to integer
  int input_value = std::stoi(input_string);
  int output_value = input_value * input_value;
  std::cout << "This value squared is " << output_value << "." << std::endl;
}

This examples assumes that there is a file named 'input.txt' in the working directory that contains a number.

An input file stream is first created using the ifstream class. The input file is then opened. It is does not exist, then the program will exit and print an error message.

If the file does exist, the content of the file will be written into a string using the >> operator. If the input data is a number, we need to using one of the string conversion functions to convert a string into the correct data type. In this example, the file contains an integer and so we use std::stoi to covert a string to an integer. std::stod can be used to convert a string to a double.

Once the value has been converted into the correct data type, we can carry out any required operations on the number.

Supposing the input file contain '3', the following output will be displayed.

Read "3" from file.
This value squared is 9.

Note

In these examples, we have created specific input and output files streams using ifstream and ofstream respectively. Note it is also possible to create a general I/O stream (able to read and write to/from files) using the fstream class.