C++ Programming Fundamentals (Cyberrookies)
You now have a basic understanding of text file input. What about output? You may wish to write things to a file from time to time. It’s very similar to inputting a text file. Inputting a file requires the ifstream object. Outputting uses the ofstream object. The methods of ofstream are quite similar to the methods of ifstream with a few exceptions. The major methods are shown in Table 6.2.
Method | Purpose |
---|---|
open | This works just like the open method in ifstream; it opens a file. |
close | This method closes a previously opened file. |
attach | This attaches your current stream to an existing file. It is useful if you wish to append the contents of your stream to another file. |
is_open | This property returns true if the file is open. |
seekp | This method sets the pointer location in the file. |
tellp | This method retrieves the current pointer in the file. |
write | This method writes a sequence of characters to a file. |
This next example opens a file, then writes text to it. All of this is done using the ofstream.
Example 6.2
Step 1: Open your favorite text editor and enter the following code.
#include <fstream> int main () { ofstream myfile ("test2.txt"); if (myfile.is_open()) { myfile << "This outputting a line.\n"; myfile << "Guess what, this is another line.\n"; myfile.close(); } return 0; }
Step 2: Compile the code.
You can see that this code is quite similar to the file input code. Note that the <<operator is used here, just as it was with cout. C++ tries to make input and output very similar whether it’s screen/keyboard or files. These previous two examples demonstrate the basics of input and output of text files. You will use these techniques again later in this book.
Категории