ofstream and Output

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.

Table 6.2: ofstream Methods and Properties




This works just like the open method in ifstream; it opens a file.


This method closes a previously opened file.


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.


This property returns true if the file is open.


This method sets the pointer location in the file.


This method retrieves the current pointer in the file.


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.

C++ Programming Fundamentals
C++ Programming Fundamentals (Cyberrookies)
ISBN: 1584502371
EAN: 2147483647
Year: 2005
Pages: 197
Authors: Chuck Easttom

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net