๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

C++ Writing Files

File output is the writing of program data into a file. The file keeps the data after the program ends.

Writing two lines and reading them back

The output stream writes two lines to notes.txt. The program closes the file, reads it back, and prints both lines.

#include <iostream>
#include <fstream>
#include <string>

int main() {
  std::ofstream out("notes.txt");
  out << "First note\n";
  out << "Second note\n";
  out.close();
  std::ifstream in("notes.txt");
  std::string line;
  while (std::getline(in, line)) {
    std::cout << line << "\n";
  }
  return 0;
}

Adding a line with append mode

The first stream writes two lines and closes. A second stream in append mode adds a third line at the end.

#include <iostream>
#include <fstream>
#include <string>

int main() {
  std::ofstream out("notes.txt");
  out << "First note\n";
  out << "Second note\n";
  out.close();
  std::ofstream app("notes.txt", std::ios::app);
  app << "Third note\n";
  app.close();
  std::ifstream in("notes.txt");
  std::string line;
  while (std::getline(in, line)) {
    std::cout << line << "\n";
  }
  return 0;
}

Writing numbers with a loop

The loop writes four numbers, one on each line. The program reads the numbers back and prints their sum.

#include <iostream>
#include <fstream>

int main() {
  std::ofstream out("numbers.txt");
  for (int i = 1; i <= 4; i++) {
    out << i * 10 << "\n";
  }
  out.close();
  std::ifstream in("numbers.txt");
  int number;
  int sum = 0;
  while (in >> number) {
    sum += number;
  }
  std::cout << "Sum: " << sum << "\n";
  return 0;
}

Example

#include <iostream>
#include <fstream>
#include <string>

int main() {
  std::ofstream out("diary.txt");
  out << "Walked in the park\n";
  out << "Read a book\n";
  out.close();
  std::ofstream app("diary.txt", std::ios::app);
  app << "Cooked dinner\n";
  app.close();
  std::ifstream in("diary.txt");
  std::string line;
  while (std::getline(in, line)) {
    std::cout << line << "\n";
  }
  return 0;
}

Key points

  • The <fstream> header gives a program the file stream types.
  • std::ofstream is the type for a stream that writes to a file.
  • std::ifstream is the type for a stream that reads from a file.
  • An output stream opened with a file name creates the file when the file is missing.
  • The << operator writes values to an output file stream.
  • The std::ios::app mode adds new data at the end of a file.
  • The close method ends work on a file stream.

In this example, the first stream writes two diary lines to diary.txt. The second stream appends a third line at the end of the file. The read back prints all three lines in order.

Note

A stream that fails to open tests false.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which mode adds new data at the end of a file?