Up

Reading and Writing on a Text File in C++

 

The following is a sample program in C++ to read and write on a text file.

 

#include <iostream>

#include <fstream>

 

using namespace std;

 

int main(){

        cout << "Input File Name = ";

        char nm[100];

        cin >> nm;

        ifstream fin;

        fin.open(nm);

        cout << "Output File Name = ";

        cin >> nm;

        ofstream fout;

        fout.open(nm);

       

        char str[1000];

        while(!fin.fail()){

                char str[1000];

                fin.getline(str, 1000);

                fout << str << endl;

        }

        fin.close();

        fout.close();

 

        return 0;

}

 

Letfs run the above program gRdLN.cpph with input text file gData.txth and output text file gCheck.txt.h The name of the output file is arbitrary.

Figure 1 shows Data.txt.

Figure 1. (Line numbers 1 to 10 are shown on the left )

 

Figure 2 shows the terminal display, on which the program was run.

Screenshot1

Figure 2

 

Command g++ built an executable file gprgLNh from the source code file gRdLN.cpp.h

In the case of Figure 2, Data.txt (the input file) and CheckLN.txt (the output file) are in the same folder as the program, i.e., in the current directory.

Figure 3 shows output file eCheckLN.txt.h

Figure 3

 

Change the following code of the above program

fin.getline(str, 1000);

to

fin.getline(str, 5);

Then, we get the following program.

 

#include <iostream>

#include <fstream>

 

using namespace std;

 

int main(){

        cout << "Input File Name = ";

        char nm[100];

        cin >> nm;

        ifstream fin;

        fin.open(nm);

        cout << "Output File Name = ";

        cin >> nm;

        ofstream fout;

        fout.open(nm);

       

        char str[1000];

        fin.getline(str, 5);

        while(!fin.fail()){

                fout << str << endl;

                fin.getline(str, 5);

        }

        fin.close();

        fout.close();

 

        return 0;

}

 

Run this program, then we get the output file (Figure 4).

Figure 4

 

When the following code

fin.getline(str, 5);

reads the 4th character, i.e., the number of characters read becomes the value of the 2nd parameter – 1,

the 1st to 4th characters are set in str, and the value of the function

fin.fail()

is set to be true.

In the first example of a program, the value of function

fin.fail()

is set to be true, after the last character of the file is read by execution of code

fin.getline(str, 1000);

The timing when the value is set to be true is different from that of Visual C++.

 

 

The following program reads values written in a text file one by one.

 

#include <iostream>

#include <fstream>

 

using namespace std;

 

int main(){

        cout << "Input File Name = ";

        char nm[100];

        cin >> nm;

        ifstream fin(nm);

        cout << "Output File Name = ";

        cin >> nm;

        ofstream fout(nm);

        int v;

        fin >> v;

        while (!fin.fail()){

                fout << v << endl;

                fin >> v;

        }

        fin.close();

        fout.close();

 

        return 0;

}

 

File streams fin of stream class ifstream and fout of stream class ofstream are used in the same way as standard I/O cin and cout, respectively.

Prepare a text file shown in Figure 5.

ScreenshotA2

Figure 5

 

Run the above program as shown in Figure 6.

ScreenshotA4

Figure 6

 

We get the output file shown in Figure 7.

ScreenshotA3

Figure 7

 

 

How to extract words separated by a blank character or the like

 

Figure 8 shows a text file, which contains a line with multiple words separated by blank or tab characters.

ScreenshotB2

Figure 8

 

Consider how to extract words, e.g., gaah, gfh, and gggh from the 3rd line.

Function SeekStr of the following program extracts the (pos)th word from (char *) cstr.

 

#include <iostream>

#include <fstream>

#include <sstream>

 

using namespace std;

 

string SeekStr(char * cstr, int pos){

        stringstream strfile(cstr);

        string vs;

        for (int i = 0; i <= pos; i++){

                if (strfile.eof()){

                        vs = "";

                        break;

                }

                else{

                        strfile >> vs;

                        if (i < pos) vs = "";

                }

        }

        return vs;

}

 

int main(){

        cout << "Input File = ";

        char nm[100];

        cin >> nm;

        ifstream fin(nm);

        cout << "Output File = ";

        cin >> nm;

        ofstream fout(nm);

        while (!fin.fail()){

                char vcs[1000];

                fin.getline(vcs, 1000);

                for (int i = 0; i < 10; i++)

                        fout << i << ":<" << SeekStr(vcs, i) << ">  ";

                fout << endl;

        }

 

        return 0;

}

 

When the value of pos is too large for the corresponding word to be found, cstr is set to be gh.

Figure 9 shows the terminal on which the program was run.

ScreenshotB1

Figure 9

 

Figure 10 shows output file Check.txt.

ScreenshotB3

Figure 10

 

 

 

Conversion of a string to the numerical value

 

In the following program, execution times of two ways of conversion of a string value to the represented numerical value are compared. One is by C functions atoi and strtod, the other is by string stream class stringstream.

 

#include <iostream>

#include <sstream>

#include <time.h>

#include <stdlib.h>

 

using namespace std;

 

//              Conversion of string to int

int str2i(string str){

        stringstream sstrm(str);

        int iv;

        sstrm >> iv;

        return iv;

}

 

//              Conversion of string to double

double str2d(string str){

        stringstream sstrm(str);

        double dv;

        sstrm >> dv;

        return dv;

}

 

int main(){

        cout << "Start..." << endl;

 

        const int n = 1000000;

 

        string * vstr = new string[n], * vstrd = new string[n];

 

        time_t * t0 = new time_t;

        time(t0);

 

        //

        //                      Set string data

        //

        for (int i = 0; i < n; i++){

                ostringstream sstrm, sstrmd;

                sstrm << i;

                vstr[i] = sstrm.str();

                sstrmd << 0.1 * i;

                vstrd[i] = sstrmd.str();

        }

 

        time_t * t1 = new time_t;

        time(t1);

        double diff_time = difftime(*t1, *t0);

 

        cout << "string values..." << endl;

        for (int i = n - 3; i < n; i++)

                cout << i << ": " << vstr[i] << "   " << vstrd[i] << endl;

        cout << "diff time = " << diff_time << "s  for " << n * 2 << "values" << endl;

 

        //

        //                      Convert string to char*

        //

        char ** cstr = new char*[n], ** cstrd = new char*[n];

        for (int i = 0; i < n; i++){

                cstr[i] = new char[100];

                for (int j = 0; j < vstr[i].length(); j++)

                        cstr[i][j] = vstr[i][j];

                cstr[i][vstr[i].length()] = 0;

 

                cstrd[i] = new char[100];

                for (int j = 0; j < vstrd[i].length(); j++)

                        cstrd[i][j] = vstrd[i][j];

                cstrd[i][vstrd[i].length()] = 0;

        }

        cout << endl << "(char *) values..." << endl;

        for (int i = n - 3; i < n; i++)

                cout << cstr[i] << "   " << cstrd[i] << endl;

       

        //

        //              Convert char* to int or double

        //

        int  * ivalues = new int[n];

        double * dvalues = new double[n];

        char * ept;

        int gn_rep = 20;

        cout << endl << "Conversion by C functions..." << endl;

        time(t0);

        for (int k = 0; k < gn_rep; k++)

                for (int i = 0; i < n; i++){

                        ivalues[i] = atoi(cstr[i]);             //              C function

                        dvalues[i] = strtod(cstrd[i], &ept);    //              C function

                }

        time(t1);

        diff_time = difftime(*t1, *t0);

        cout << "diff time/C = " << diff_time << "s  for atoi and strtod functins." << endl;

        cout << "Converted values..." << endl;

        for (int i = n - 3; i < n; i++)

                cout << ivalues[i] << "   " << dvalues[i] << endl;

 

        //

        //              Convert string to int or double

        //

        cout << endl << "Conversion by stringstream objects..." << endl;

        time(t0);

        for (int k = 0; k < gn_rep; k++)

                for (int i = 0; i < n; i++){

                        ivalues[i] = str2i(vstr[i]);            //              Defined above

                        dvalues[i] = str2d(vstrd[i]);           //              Defined above

                }

        time(t1);

        diff_time = difftime(*t1, *t0);

        cout << "diff time/S = " << diff_time << "s  for stringstream objects." << endl;

        cout << "Converted values..." << endl;

        for (int i = n - 3; i < n; i++)

                cout << ivalues[i] << "   " << dvalues[i] << endl;

 

        cout << endl << "Deleting objects..." << endl;

        delete [] vstr;

        delete [] vstrd;

        delete t0;

        delete t1;

        for (int i = 0; i < n; i++){

                delete [] cstr[i];

                delete [] cstrd[i];

        }

        delete [] cstr;

        delete [] cstrd;

        delete [] ivalues;

        delete [] dvalues;

               

        return 0;

}

 

 

Figure 11 shows the terminal on which the above program was run.

Figure 11

 

A sample program, which shows how to use a multidimensional array of string type data, is prepared at this website.

 

Up