C++ file io Management

Spread the love

C++ file io management – what that really means

File management in any language really means – “How we store the data that is important to us”. In C and C++ this could also technically mean storing data to a stream, where that stream could be a file or could be some kind of output such as a console, network, printer, live video stream, etc.

In our case, the how will be straight storage as well as CSV and JSON file formats

So far, most of the c++ coding examples shown so far have concentrated on syntax and other aspects of c++ but haven’t dealt with saving our results to file. For this example, you won’t be able to use http://cpp.sh because an online compiler is really running in a sandbox of sorts and it wouldn’t make sense trying to save your work remotely on someone else’s machine.

c++ file io management image showing the possible input sources moving to an input stream towards the c++ program. An output stream arrow shows data moving towards a sink like a console, file network or program

So for this c++ file io example, you will have to ensure that you have a local IDE with a compiler that you can use on a system that you can save to.

The following classes are going to help us with the input/output process. To be truthful, we have used parts of these classes already with our use of cout and cin.

  • ofstream: Stream class to write on files
  • ifstream: Stream class to read from files
  • fstream: Stream class to both read and write from/to files.
/*
  Reason for being: Show the writing of plain data 
  to the output stream
  c++ file io sample code

*/

#include <iostream>  // been using this all along
#include <fstream>   // new for our lessons so far

using namespace std;

int main () {
  char gotIt[255];
  cout << "What should we write to the file ?\n";
                          // if we use cin >> gotIt, 
  cin.getline(gotIt,255); // we get the first word only

  // open the output file
  ofstream outPutFile;
  outPutFile.open ("myOutPut.txt");  // crude but effective
  outPutFile << "Writing this to a file.\n";
  outPutFile.close();
  return 0;
}

To keep things simple, we didn’t do a number of things that would make the above code appear to be more complicated. We didn’t use std:: We didn’t check to see if the file that we tried to open, actually opened or not. We didn’t try to open the file in any specific mode. Yes, we could have used append mode.

Note: If you are using sublime text on a Mac, the std::cin or cin >> line will cause program execution to somehow mysteriously stop. Its not actually so mysterious, the problem is that Sublime text, while a great editor is not actually an IDE and as such its opening a terminal window to run the program. The terminal window won’t accept the input from cin in this fashion. Sorry, you will have to open the terminal window manually then type g++ appNameThatYouUsed then ./a.out to run the application.

Let’s do some more c++ file io again

This time, we will keep it really quite simple. Yeah, we should have done that the first time, right? ha ha.

#include <fstream>

using namespace std;

int main(){
    ofstream f;
    string myWord = "It simply couldn't get much simpler\n";
    f.open("myOutPut.txt");
    f << myWord;
    f.close();
}

Yep, try it. That compiles and runs and overwrites whatever was in the myOutput.txt file.

C++ file io write without overwriting file contents

#include <fstream>

using namespace std;

int main(){
   ofstream f;
   f.open("myOutPut.txt",ios::out | ios::app);
   f << "Yeah, no string arrays this time, just use this";
   f.close();
}


So, this works too and it does not overwrite.

  • ios::out // is opening the file for output
  • ios::app // means that your output mode is going to be append, not overwrite

c++ file io with csv

You thought this part was going to be hard, right?

CSV files are comma delimited files that do not have an initial row with titles that help to define the columns beneath.

  • “George”,”Stevens”,89,56,90,85
  • “Samuels”,”Sawchuck”,89,56,90,85
  • “Robert”,”Smith”,89,56,90,85
  • “Janice”,”Merkel – Stevens”,89,56,90,85
  • “D’arcy,”Mason”,89,56,90,85

Above, we have 5 students who somehow managed to get the exact same grades for all 4 exam results. Coincidence? Yeah, definitely beyond the scope of this lesson!

The data would be written to a file in exactly this fashion seen above.

Note that Strings are delimited with either double quotation marks or single quotation marks but you can’t switch mid-stream.

For better consistency with existing csv files, we suggest strongly that you use double quotation marks as a string delimiter so that you can use the single quote for things like D’arcy

Ending each string with a \n or null symbol \0 would be advisable

So, how difficult is this c++ file io csv snippet to code?

Relatively simple, especially if we cheat and just add the data seen above to 5 student variables and quickly test.

#include <fstream>

using namespace std;

int main(){
   string st1 = "'George','Stevens',89,56,90,85\n";
   string st2 = "'Samuels','Sawchuck',89,56,90,85\n";
   string st3 = "'Robert','Smith',89,56,90,85\n";
   string st4 = "'Janice','Merkel - Stevens',89,56,90,85\n";
   string st5 = "'D\'arcy','Mason',89,56,90,85\n";

   ofstream f;
   f.open("myOutPut.txt",ios::out | ios::app);
   f << "\n" << st1 << st2 << st3 << st3 << st4 << st5;
   f.close();
}

Clumsy, awkward and contrived but it works.

Perhaps what we should really do is to ask the user to input a name and 4 scores, five (5) times, then write that information with the commas into the file.

This c++ file io lesson is getting a bit long in the tooth.

Why don’t we explore the csv format and the json file format more strongly in the next lesson.

Top