Writing or reading from/to a specific source might be acceptable for specialized applications. In spite of that, typically we should separate the way our program reads and writes from the actual input and output device; therefore, this avoids us the urge of directly address specific approaching for each different device (changing our program for each screen or disk in the market) or only use a limited amount of screens or disks that we happen to like,and by this, limiting our clients.

Nowadays, operating systems separate the details of handling specific I/O devices into device drivers allowing programs to access through a generic I/O library which encourage a better development.

The C++ Standard provides I/O libraries to define output and input for every built-in type, but in this article we’re going to focus on 3 specific stream libraries:

  • fstream for reading from a file and writing to a file in the same stream.
  • ofstream converts objects in memory into streams of byte and writes them to the file.
  • ifstream takes streams of bytes from the file and composes objects from it.

Write a File steps

The following snippet shows the basic- recommend steps to write a file using C++:

#include <iostream>
//Header for I/O file streams
#include <fstream>

using namespace std;

int main(){
    //1. Name it (or create it) for writing
    ofstream ofs ("test.txt",ios_base::out);
    //2.- Open it
    if(ofs.is_open()){
    //3.- Write out objects
        ofs<<"Hello C++"<<endl;
        for(unsigned int i=0;i<5;i++)
            ofs<<"Paragraph: "<<i<<endl;
     //4.-Close
        ofs.close();
    }
    //0. Hold errors.
    else{ //Error
        //...
    }
    return 0;
}

Read a file steps

The coming snippet shows the basic- recommend steps to read a file using C++, this program reads the content of the file and shows the same content in the output console window:

//... Read it and show it
    //Read
    //1. Know its name
    ifstream ifs{"test.txt",ios_base::in};
    if(!ifs){ cout<<"can open input file text.txt"<<endl;}
    else{
        //2. Open it
        string temp;
        temp.clear();

        //3. Read in the characters
        while(ifs){
         ifs>>temp;
         cout<<temp;
        }
    }
    //4. Close (Implicitly closed)
    //ifs.close();

Exercises

The next exercise creates a file of data in a specific format <hour (0-23), temperature (ºC)>.

The row (1) demonstrates how to create a file with a specific version and mode (in this case, for writing the file).

The row (2) shows how to handle errors (displaying a error message and ending the program). Various C++ authors recommend to check for errors just after the creation/opening of the file.

The (3) represents the format we’re writing in the file <12 56C>.

int main(int argc, char *argv[])
{
    
    ofstream os{"raw_temps.txt",ios_base::out}; //(1)
    if(!os.is_open()){ //(2)
        //hold error
        cout<<"The file produces a error"<<endl;
        return 1;
    }
    bool cont_flag=true;


    cout<<"[Welcome to the Temperature File creator]"<<endl;
    do{
        int tempHour;
        int tempTemp=0;
        char cDecision;
        cout<<"Type the hour (0 to 23): "<<endl;
        cin>>tempHour;
        cout<<"Type the temperature (ºC): "<<endl;
        cin>>tempTemp;
        os<<tempHour<<'\t'<<tempTemp<<'C'<<'\n'; //(3)
        cout<<"Do you want to add another pair? Y-N "<<endl;
        cin>>cDecision;

        cont_flag=(cDecision== 'Y' || cDecision== 'y')?true:false;
    }while(cont_flag);
    return 0;
}

So far, that’s it! I hope you enjoy this article.

Leave a Reply

Your email address will not be published. Required fields are marked *