Writing Data to a File with ofstream
C++ file streams are used for reading from and writing to files.
Why Programs Need File Streams
Many programs need to exchange information with files stored on disk. A program may need to get information out of a file so it can use that information, put information into a file so the result is saved, or do both. C++ handles this exchange through file streams. A file stream is the tool a program uses to move data between itself and a file on disk.
File streams do not all play the same role. The source identifies three types, and each one is suited to a different kind of job. So the practical question this section answers is: when a program opens a file, which stream type should it pick? Answering that question well starts with a clear picture of what each type is for, and of the direction in which data moves.
This article focuses on ofstream, the type used for writing. You will also see how it differs from ifstream and fstream, because choosing the right stream depends on comparing them.
Tracing the Direction of Data
Before naming any types, trace the path the data takes. There are only two places data can live in this picture: inside the running program, and inside the file on disk. A stream is the channel between them, and the question is which way the data travels.
Read the arrows as the whole lesson. The arrow pointing from the program toward the file is the direction ofstream handles. The arrow pointing from the file into the program is the direction ifstream handles. A program that needs both arrows needs the combined type, fstream.
The Three Stream Types and Their Jobs
ifstream is the stream type for reading from a file. It supports input operations, so it carries data into the program.
ofstream is the stream type for writing to a file. It supports output operations, so it carries data out of the program and into the file.
fstream is the stream type for both reading from and writing to a file. It is the type the source names for input and output together.
The names themselves carry the hint. The name ifstream comes from input, the direction in which data flows into the program. The name ofstream comes from output, the direction in which data flows out of the program. The name fstream covers the file work in general, and the source ties it to the combined job of reading and writing.
| Stream type | Data direction | Typical job |
|---|---|---|
| ifstream | Into the program (input) | Pull data from a file so the program can work with it |
| ofstream | Out of the program (output) | Record results, save output, or produce a file |
| fstream | Both directions | Read from a file and also write to it |
The three file stream types and the direction of data each one handles
Notice that fstream does not replace the other two in every case. It is the type the source identifies for the combined job. When a task needs only one direction, the single-direction type matches the task more directly.
Writing Results with ofstream
ofstream is the mirror image of ifstream. Where ifstream carries data into the program, ofstream carries data out of the program and into a file. When the task is to record results, save output, or produce a file, ofstream is the stream type that fits.
Choosing ofstream for a results-saving task
A program calculates a list of final scores for a class. The teacher wants those scores saved into a new file on disk so they can be shared later. Which stream type should the program use?
- 1Identify the job
The program produces scores and must save them to a file. The task is to record results.
- 2Identify the direction of the data
The scores start inside the program and must go into the file, so the data moves out of the program.
- 3Match the direction to a type
Data moving out of the program into a file is the job ofstream is for, since ofstream is the stream type for writing to a file.
- 4Check for a second job
The program does not need to read the file back during this task, so the combined type is not required.
The program should use ofstream.
What do you think happens?
A program must read a settings file, then append a log line to the same file. Which stream type does the task need?
Reveal answer
fstream
The task has two jobs on one file: reading the settings and writing the log line. The source identifies fstream as the type for both reading from and writing to a file, so it covers the combined job that neither ifstream nor ofstream handles alone.
Mapping a Task to a Stream Type
The source gives a direct mapping from job to type. Choosing a stream type comes down to one question: what does the program need to do with the file? Read the task, identify the direction of the data, and pick the matching stream. The flowchart below follows that path.
Choosing ifstream for a reading task
A program must load a list of player names stored in a file so that it can display them on the screen. Which stream type fits?
- 1Identify the direction
The names are stored in the file and must come into the program, so data moves into the program.
- 2Ask the flowchart questions
The task reads from the file. The program does not need to write back to it, so the path leads to ifstream.
- 3Confirm the match
ifstream is the stream type for reading from a file, supporting input operations.
The program should use ifstream.
A game saves the player's high score to a file at the end of each round. Which file stream type should it use, and why? Explain in terms of the direction the data moves.
Hints
- Ask first whether the score moves into the program or out of it.
- Saving the score is recording a result, which is the job the source gives to ofstream.
Mistakes When Choosing a Stream Type
The most common errors come from reasoning about the file rather than about the task. The checks below help avoid them.
Common mistake Choosing a stream by the file's name or contents instead of the job
Why it failsThe source ties the choice to what the program needs to do with the file, not to what the file contains.
Do this insteadDescribe the task first: read, write, or both. Then pick the matching type.
Common mistake Using ofstream when the program also needs to read the file
What it looks likeA program writes a log line and then reads the log back to check it, but only ofstream is chosen.
Why it failsofstream supports output only. A task with both jobs matches fstream, the type the source names for reading and writing together.
Do this insteadUse fstream when the task includes both reading and writing.
Common mistake Assuming fstream should always be used because it covers everything
Why it failsThe source says fstream does not replace the other two in every case. It is the type for the combined job.
Do this insteadUse ifstream for reading only and ofstream for writing only when the task needs just one direction.
Common mistake Mixing up the names of ifstream and ofstream, since the direction is the opposite of what a beginner might expect from the word alone
Summary of Stream Choices
At a glance
- C++ file streams move data between a program and a file on disk, and a program may read, write, or do both.
- ifstream is the stream type for reading from a file, carrying data into the program.
- ofstream is the stream type for writing to a file, carrying data out of the program into the file.
- fstream is the stream type for both reading from and writing to a file, and it is chosen when a task needs both jobs.
- Choose the stream type by identifying the direction of the data the task requires, then picking the matching type.