Brief
File Basics
C++ provides the fstream
(file stream) library to perform output and input of characters to/from files. The library presents us with two objects:
- ofstream: Stream class to write to files (output file stream)
- ifstream: Stream class to read from files (input file stream)
To create ifstream
objects and ofstream
objects we write the following code:
To modify files, it is required to open them. Once your modifications are done, you can close the file.
For the case of inFile
, you must open a file by calling the object’s open
method before performing read operations on it.
Once you are done operating on your file, you are to close the file.
When one does not want to access data that is past the end of the file, use inFile.eof()
which returns a boolean representing whether the end of the file has been reached.
Writing to Files
With an ofstream
object, you are able to write to files.
The code above opens myFile.txt
using the ofstream
object outFile
. It then writes the values of doubleNum
and intNum
into the file. Notice that between writing the values into the file, a whitespace is written. This is done so that the numbers are kept separate and could be read back individually. Following the new line, a full sentence is then written to the file.
Reading From Files
With an ifstream
object, you are able to read from files. There are multiple ways of approaching this:
The code above opens myFile.txt
using the ifstream object inFile
. It then reads in the values 2 and 5 into doubleNum
and intNum
respectively. To read a line from the the file, the getline()
function is used.
Writing and Reading Binary Objects
Applying what we learned above, we will read and write binary objects into and out of a file.
There are a few differences when dealing with binary objects. When you plan on writing an object to a file, you need to specify you will be appending to the file by including the ios::app
flag in the open
method. When writing, you will pass two parameters to the read
method: a character pointer to your object and the size of the object.
- Previous
- Next