Skip to main content

Section 6.3 File Operations

Having created a stream with the declaration above, we can connect it to a file (i.e. open the file) using the member function open(filename). For example, the following statement will allow the C++ program to open the file called “myFile.txt”, assuming a file named that exists in the current directory, and connect in_stream to the beginning of the file:
in_stream.open("myFile.txt");
Once connected, the program can read from that file. Pictorially, this is what happens:
Figure 6.3.1.
the <ofstream> class also has an open(filename) member function, but it is defined differently. Consider the following statement:
out_stream.open("anotherFile.txt");
Pictorally, we get a stream of data flowing out of the program:
Figure 6.3.2.
Because out_stream is an object of type <ofstream>, connecting it to the file named “anotherFile.txt” will create that file if it does not exist. If the file “anotherFile.txt” already exists, it will be wiped and replaced with whatever is fed into the output stream.
To disconnect the ifstream in_stream from whatever file it opened, we use its close() member function:
in_stream.close();
To close the file for out_stream, we use its close() function, which also adds an end-of-file marker to indicate where the end of the file is:
out_stream.close();
Answer the question below concerning the use of the fstream library:

Reading Questions Reading Question

1.

Say you wanted to add some text to a file that already has important information on it. Would it be a good idea to first use ofstream to open the file?
  • Yes, ofstream is required to edit the file.
  • Wrong! Even though it is required for editing files, using ofstream first will cause problems when it opens a file that has previous work saved on it.
  • Yes, using ifstream will wipe the file clean without using ofstream first.
  • Wrong! ifstream is only used to read files, therefore it will never edit the contents of one.
  • No, using ofstream on a file that already has information on it will clear the entire file.
  • Correct!
  • No, ofstream is exclusively used for reading files.
  • Wrong! ifstream is used to read files instead.
You have attempted 1 of 2 activities on this page.