Adding File I/O to a C++ Program

We have already covered console reads from the keyboard and writes to the display using cin and cout. If you do not know how to use cin and cout, please review it before proceeding. ifstream is for an input file connection and an ofstream is for an output file connection. Once set up, they can be used the same as cin and cout respectively. Both ifstream and ofstream are C++ classes and so you need to create an instance of each class in order to use it. You have been using classes throughout your coding work with C++. The one that is easiest to explain is the class “string”. String is a class and the name of your string is the instance of the class. In your header section, it would described as:

string myString = "This is a string."

later in the code, you might want to find its length.

int len = myString.length();           // This finds the length of the string store in your instance of string.

To be fair, there are five different ways to find the length of a string. The first four are more useful than the fifth. https://www.geeksforgeeks.org/5-different-methods-find-length-string-c/

length() is considered a method of the class string and can be called by adding it to the instance of the class string by adding a “.” and then the name of the method to the instance name, as seen in the example above.

Now getting back to ifstream and ofstream.  First create the instance of each class to use.

ofstream outFile;       // define the interface to the file for writing information.
ifstream inFile;        // define the interface to the file for reading information.

The next thing to do is to open the file and seek the start of the file, again done by two methods:

   inFile.open(fileName);
   inFile.seekg(0);

Now to read something from the file one line at a time until no more lines are left in the file and divide up the line into phrases that are separated by commas:

for (string line; getline(inFile, line); ) {   // Read a line, stopping at newline (\n), keep going until EOF (end of file).
       stringstream stream(line);                // Set up the line to be readable through a stream.
      index = 0;
      while (getline(stream, word[index], ',')) {
          cout << headers[index] << word[index] << "\n";
          index++;
      }
      sum += stod(word[2]);
      count++;
 }

Output to a file is even simpler, First open the file. You have to see if the file exists. If it does, give the user the choice to write over the file or append to the file. If the file does not exist, create it.

if (isFileExist(fileName)) {
     // The file exists, so give the user the choice to start a new file or append to the existing file.
     int appendToFile = stoi(input("Do you want to:\n1) Open fresh file?\n2) Append to current file?\nChose"));
     switch (appendToFile)
     {
        case 1:
           outFile.open(fileName);     // Open an existing file, overwriting current content..
           break;
        default:
           outFile.open(fileName, fstream::app); // Open an existing file and allow appending new data.
           break;
      }
}
else outFile.open(fileName, fstream::out);  // Force the creation of the file and then open.

Once you have opened/created the file you can write to it just like you do to the console through cout.

 outFile << employee << "," << birthdate << "," << wages << endl;

The above code will write a comma separated list with three fields to one line in the file. Be sure to close the files when you are done.

outFile.close();
inFile.close();
This entry was posted in Uncategorized. Bookmark the permalink.