Main Content

Reading (and writing) files in C++

Archive - Originally posted on "The Horse's Mouth" - 2012-07-18 23:30:23 - Graham Ellis

"But how do I read data from a file ....?". Question on a C++ course on which we had concentrates, thus far, on object orientation.

In summary:
1. Include the fstream header file
2. Create an object of type ifstream using the constructor, and passing in the file name
3. Read lines from the ifstream object using the getlines method
4. Check for end of file using the eof method

In code:
  #include <fstream>
  ifstream infile("requests.xyz");
  infile.getline(myline,256);
  if (infile.eof()) break;

with the latter two statements in a loop. Complete source [here].




Writing a file? use an ofstream!

I've added a full example of input and output [here] on our web site.

In the example, a file (named on the command line) is read in line by line, and is combed - i.e. a sample of one line in every 10 (or 15, or 20, or any other number given on the command line) is output - either to the screen, or to an output file if one is named on the command line.

The program includes extensive (but NOT complete) data validation, checking whether the files open correctly, and whether the correct number of parameters were given on the command line.




We offer a range of C and C++ courses - for newcomers to programming, as well as to delegates with prior programming experience. See [here] for details.