C++ Programming Series: File I/O

In this post, we are going to discuss about input and output. No, I am not talking about cout, cin, getline() or any other methods we have discussed till now. I am talking about writing and reading files.

For working with files, we need to include another header called fstream.

There are three classes in it, for file I/O:

  • ofstream – Class for writing files
  • ifstream – Class for reading files
  • fstream – Class for writing as well as reading files

We are going to discuss ofstream and ifstream only. fstream is a bit different to use but who cares! We don’t need that!

The codes for file I/O are present below. It is pretty simple and there is more comment in the code than the code itself, for explaining things!

File Writing:

#include <iostream>
#include <fstream>

using namespace std;

int main()
  //The 'ofstream' class for writing a file
  ofstream fileWriter("a_file.txt");

  int number = 21;

  //Writing the stuff
  fileWriter << number;
  fileWriter << " ";
  fileWriter << 13;

  //Closing that file which is opened; it is important!

  return 0;

File Reading:

#include <iostream>
#include <fstream>
using namespace std;

int main()
  //The 'ifstream' class for reading a file
  ifstream fileReader;

  //Opening a file called 'a_file.txt' in local directory

  //For checking whether the file fails to open or not
  if (fileReader.fail())
    cout << "There is no file in the address!" << endl;

  //While the file that is opened, has some context
  //in it at the pointer location
  while (fileReader.good())
    //Variable to store reading from the file
    int number;

    //Reading the number at the pointer location and then,
    //proceeding the pointer forward for further reading
    fileReader >> number;

    //Displaying the number present in the file
    cout << number << endl;

  //Closing that file which is opened; it is important!

  return 0;

Reading and writing a file requires us to have the concept of a pointer. The pointer points to some place in the file which then, proceeds forward with every single read/write operation. That pointer is similar to the one which appears at the time of typing.

I hope that you understood how to read and write a file. But there are still some doubts and confusions!

The first one is the formatting of the file that we are reading. White spaces are something that no one wants to read/get from the file. So, ifstream don’t consider these spaces and no matter how much white space there is, it will be considered as one space only.

Of course, we can’t just read data as discrete if that data is arranged without spaces in between. For example, if the file contains two words without any space like this, “nospace”, ifstream reads it as “nospace” and so, giving a space between them rectifies the issue.

The second one is the data type for reading and writing a file. We can use all primitive types. We can use strings as well if we include the string header.

The third one is formatting a file being written. We can have formatting by just writing in character literals like \t or \n to have a tab or a new line respectively.

This is how we simply read and write files. Now, your task is to modify the registration program that we made with functions previously, to write a file with the data inputted by the user.

Soon we will see, how much fun is programming! It is fun for me as I am developing a game in C++ called SamuraiDuel.


C++ Programming Series: Functions/Subroutines (Part 4, Last)

In the previous post, I confused you into the depth of the functions and my abstractions although, I hope that you got the concept fairly. The hint that I gave you in the previous post is about the order of the functions. If you modified checkRegistrationEligibility() function by adding enterAString() and enterAnInt(), you may have got some error because checkRegistrationEligibility() function don’t know anything about enterAString() and enterAnInt() since, they are both defined as well as declared below the function. The issue with the order of the functions can be fixed but I will explain this later!

The functions with which we get father’s name, place of living and education in the previous post are very similar to each other. In fact, they are just the same with the exception to the statement being printed out!

Fortunately, there are more ways! Until now, we are just getting outputs from the functions in the form of returning values. But in many cases, it is necessary to have inputs in the functions. If you recall the first post on the topic of Functions/Subroutines, we discussed that a function takes the input, modifies it and then, outputs the modified input. We can always have the user input but there are many many cases where user input is not the solution! A pair of round brackets after the end of each function is not useless; it is for taking data into the function(inputs) or in other words, for taking parameters.

I had given you the task for creating a function which takes the user input for the number to be squared and then, returns the square of that number. Here it is done with a function that takes the input from the parameter, squares it and then, returns it.

int square( int value ) //a parameter of type 'int'
  return (value * value);

int main()
  //In 'square' function, we pass 5 as a parameter, giving us 25 as a return value.
  cout << square(5) << endl; //Outputs 25
  return 0;

This might have given you the idea of how parameters of a function works. Let us remove the three functions as described in the previous post namely, enterYourFatherName(), enterYourPlace() and enterYourEducation() and replace it with only one function!

string enterRequiredData( string required_data ) //a parameter of type string
  string data = "NULL";
    cout << "Enter your " << required_data << ": " << endl;
    data = enterAString();
    cout << "Is your " << required_data << " " << data << "?" << endl;
  } while (!isDataSure());

  cout << "Your " << required_data << " is " << data << "." << endl;
  return data;

Now, in the registrationSection() function:

void registrationSection()
  enterRequiredData("father\'s name");
  enterRequiredData("place of living");

All the other codes will remain same! You can see that a single function is doing quite a job because of the fact that it is more flexible now. The output of a function should depend on the parameters being given into it or else, the function should have no inputs/parameters at all. However, it is not necessary to use the output of a function for something else. In the codes above, we haven’t used the strings being returned by the functions inside the registrationSection(). We can store them in a separate file which is the prime purpose of registration (We will discuss about getting data into and out of a file soon).

That’s all! Function parameters are awesome! But there are still few problems that we may encounter, the first one is the order of functions and the second one is getting multiple outputs. You haven’t seen any example of multiple inputs/parameters as well. There you go!

int clamp(int value, int min, int max)
  if(value < min)
    return min;
  else if(value > max)
    return max;

  return value;

Try to code functions with multiple parameters and have fun with them!