Video Coming Soon...

Created by Zed A. Shaw Updated 2026-04-30 02:05:52

21: Writing to a File

In this exercise you'll learn the basics of writing to a file. The process is mostly the same, just in reverse. You open file. You write lines to file. You close file. We'll do this a bit differently from the previous. I'll give you a "starter" code that's very simple, then give you a challenge to complete based on this code.

The Code

Code for this exercises:

View Source file ex21.cpp Only

#include <vector>
#include <fmt/core.h>
#include <iostream>
#include <fstream>

using std::vector, std::string, std::ofstream, std::ios;
using fmt::println;

int main(int argc, char *argv[]) {
  vector<string> names{
    "Frank", "Joe", "Mary", "Thompson"
  };
  ofstream outfile{"names.txt"};

  for(auto& name : names) {
    outfile.write(name.c_str(), name.size());
    outfile.put('\n');
  }
}

This exercise will be a challenge style exercise where you take the above code and use the previous exercises to create a program that reads from a file, asks the user for input, and writes to a file.

The Breakdown

int main(int argc, char *argv[])
Your main entry function.
vector<string> names{
This is how you create a vector that already has strings in it.
"Frank", "Joe", "Mary", "Thompson"
You can put as many of these as you want, and they can be on multiple lines. Separate them by , (commas).
};
This ends your initialized vector of string.
ofstream outfile{"names.txt"};
This creates an out file that will go to names.txt on your computer.
for(auto& name : names) {
Iterate through each name in names. You'll learn what the & (ampersand) does in the next module, but it's a "reference operator."
outfile.write(name.c_str(), name.size());
This writes the contents of name to the file. You have to do it this way so that the write() function knows how much data to write.
outfile.put('\n');
This writes a single character to the file, which will add a \n (newline) character.

The Challenge

I am now going to present a series of challenges to you related to this code:

  1. Find all of the documentation on cppreference.com.
  2. Make it possible to pass a name to the program instead of just name.txt.
  3. Use what you know to prompt the user for a series of names instead of loading names in the code.
  4. Write another version that can load the file, putting everything into names, then prompt the user for more names.
  5. ADVANCED: Turn this into a "name list database" that lets people load a list of names, create, read, update, and delete the names from the list.

The Practice

You should now attempt each of these to become more solid in your abilities:

Change It
Take this code and change it in some way. Remember, the changes don't have to be amazing. Any simple change will do.
Break It
Try to find novel ways to break this code. Try some syntax errors, feeding it bad data, etc.
Recreate It
Write a description of this code in your own words, then try to recreate it from your description. Remember that you can always look at your original if you get stuck, but hide away again after you take a peek.

Further Study

We are at the end of the Input/Output phase of C++. I've taught you a very baby "Grug Brained" version of I/O that will be just enough for you to continue. It's definitely not what most C++ people use, but honestly most C++ people don't really do a whole lot of file I/O. They're too busy crashing the stocks of AAA game companies with constant rewrites of games. To further your education, start studying the standard C++ I/O here:

https://en.cppreference.com/cpp/io

It's dense so to get a decent first example read this and implement the example:

https://en.cppreference.com/cpp/io/cout

Then read about cin:

https://en.cppreference.com/cpp/io/cin

This isn't necessary to continue the course, but it's a good study topic if you're interested.

Previous Lesson Next Lesson

Register for Learn C++ the Hard Way

Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.