Working with Text Files - C++

Inputting and outputting to files is exactly like inputting and outputting onscreen because the cin and ifstream classes are both derived from the istream class, as shown earlier in Figure . Likewise, cout and ofstream are both derived from the ostream class. Both use the overloaded insertion operator <<.

The following code exemplifies this point:

Output:

Copper Dragon
Bronze Dragon
Silver Dragon
Gold Dragon

“dragons.txt” will normally be in the same folder as your project. However, if you don’t find it there, go to the Windows taskbar, click Start, Find (or Search), Files or Folders. A window entitled something like Find: All Files will appear. Type the name of the file and select the drive on which it is stored. Then click Find Now, and Windows will find the file for you. (Note that your program might have slightly different names.)

If you run the program twice, you will notice that the text file always contains the same information. This is because the implied ios::trunc uses the ofstream class if you do not specify mode parameters. Remember that ios::trunc restarts a file if it already exists.

Although you can input from the file with the overloaded shift operator (>>), it becomes impossible to know when you reach the end of your file. The easiest way to input from a text file is to input the data line by line using the istream::getline() method. This is also the most useful method because most data are stored line by line, so you input the line and then dissect the line of data into its respective fields.

You have three options for using the istream::getline() method:

The parameter placeholders mean the following:

  • pch, puch, psch. A pointer to a char array. Remember that the getline method overwrites data stored in the array.
  • nCount. The maximum numbers that the getline method should store, including the terminating null.
  • delim. The delineating character to which getline() goes.

Last, you probably want to read to the end of a file, except how do you know where the end is? You use the ios::eof() method:

The eof() method returns a non-zero integer when the end of the file is reached.

You can put it all together now and read from the “dragon.txt” file. A sample implementation of this is shown here:

Output:

Copper Dragon
Bronze Dragon
Silver Dragon
Gold Dragon

The getline() method deletes the delineators (in this case, the default line breaks), so the program compensates by adding a line break after reading each line.

You now have read your first file!


All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

C++ Topics