|< C++ File I/O 1 | Main | C/C++ Storage Class - volatile, global, local, const, mutable etc >|Site Index |Download |


 

 

 

 

MODULE 19: C++ FILE I/O 2

------------------------------------------------------------------------------------------

MODULE 9: C FILE INPUT OUTPUT

 

 

 

 

My Training Period: xx  hours

 

 

 

19.3  Random File Processing

  • We can set position of the get pointer by using seekg().  The prototype are:

istream& seekg(streampos pos);

istream& seekg(streamoff off, ios_base::seekdir dir);

  • These commands will set the position of the get pointer. The get pointer determines the next location to be read in the buffer associated to the input stream.  The parameters:

seekg() parameter

Brief description

pos

The new position in the stream buffer of type streampos object.

off

Value of type streamoff indicating the offset in the stream's buffer. It is relative to dirparameter.

dir

Seeking direction. An object of type seekdir that may take any of the following values:

  • ios_base::beg (seek from the beginning of the stream's buffer).

  • ios_base::cur (seek from the current position in the stream's buffer).

  • ios_base::end (seek from the end of the stream's buffer).

 

Table 19.4:  seekg() parameter.

  • Try the followingseekg() member function example:

// using seekg()

#include <iostream>

#include <fstream>

using namespace std;

 

void main(void)

{

       char filename[] = "C:\\testfileio3.txt";

       fstream inputfile, outputfile;

 

       // create, open and write data to file

       outputfile.open(filename, ios::out);

       // write some text

       outputfile<<"This is just line of text."<<endl;

       // close the output file

       outputfile.close();

       // opening and reading data from file

       inputfile.open(filename, ios::in);

       // a simple error handling for files creating/opening for writing

       if(inputfile.fail())

       {

              cout<<"Opening "<<filename<<" file for reading\n";

              cout<<"------------------------------------------\n";

              cerr<<"The file "<<filename<<" could not be created/opened!\n";

              cerr<<"Possible errors:\n";

              cerr<<"1.  The file does not exist.\n";

              cerr<<"2.  The path was not found.\n";

              exit(1);   // just exit

              // 0-normal, non zero - some error

       }

       else

       {

              cout<<"The "<<filename<<" file was opened successfully!\n";

              cout<<"\nMove the pointer to the end\n"

                     <<"Then back to the beginning with\n"

                     <<"10 offset.  The pointer now at...\n"<<endl;

              // flush the stream buffer explicitly...

              cout<<flush;

             // get length of file

             int length;

             char * buffer;

             

             // move the get pointer to the end of the stream

              inputfile.seekg(0, ios::end);

             // the tellg() member function returns the current stream position.

              // there is 27 characters including white space

              length = inputfile.tellg();

             // move back the pointer to the beginning with offset of 10

              inputfile.seekg(10, ios::beg);

             // dynamically allocate some memory storage for type char...

              buffer = new char [length];

             // read data as block from input file...

              inputfile.read(buffer, length);

              cout<<buffer<<endl;

             // free up the allocated memory storage...

              delete[ ] buffer;

             // close the input file

              inputfile.close();

             // a simple error handling for output files closing

              // test if fail to close the file, do...

              if(inputfile.fail())

              {

                     cerr<<"The "<<filename<<" file could not be closed!\n";

                     exit(1);

              }

             // test if successful to close the file, do...

              else

                  cout<<"\nThe file "<<filename<<" was closed successfully!\n";

              }

       }

 

Output:

 

C++ file I/O random access

ostream& seekp(streampos pos);

ostream& seekp(streamoff off, ios_base::seekdir dir);

seekp() parameter

Brief description

pos

The new position in the stream buffer of type streampos object.

off

Value of type streamoff indicating the offset in the stream's buffer. It is relative todirparameter.

dir

Seeking direction. An object of typeseekdir that may take any of the following values:

  • ios_base::beg (seek from thebeginning of the stream's buffer).

  • ios_base::cur (seek from thecurrent position in the stream's buffer).

  • ios_base::end (seek from theend of the stream's buffer).

 

Table 19.5:  seekp() parameter.

// using seekp()

#include <iostream>

#include <fstream>

using namespace std;

 

void main(void)

{

       char filename[ ] = "C:\\testfileio4.txt";

       ofstream outputfile;

      

       // creating, opening and writing data to file

       outputfile.open(filename, ios::out);

       // simple error handling for file creating/opening test if fail to open, do...

       if(outputfile.fail())

       {

              cout<<"Creating and opening "<<filename<<" file for writing\n";

              cout<<"----------------------------------------------------\n";

              cout<<"The "<<filename<<" file could not be created/opened!\n";

              cout<<"Possible errors:\n";

              cout<<"1.  The file does not exist.\n";

              cout<<"2.  The path was not found.\n";

              exit(1);   // just exit

             // 0-normal, non zero - some error

       }

      // test if successful in creating/opening the file, do...

       else

       {

              cout<<"The "<<filename<<" file was created and opened successfully!\n";

              cout<<"\nDo some file writing....\n\n";

             

              int locate;

             

              outputfile.write("Testing: Just simple example.", 29);

             // tell the pointer position...

              locate = outputfile.tellp();

              // seek the pointer position with offset...

              outputfile.seekp(locate-16);

              outputfile.write(" rumble", 7);

              // close the output file

              outputfile.close();

              // simple error handling for output files closing

              // test if fail to close the file, do...

              if(outputfile.fail())

              {

                  cout<<"The "<<filename<<" file could not be closed!\n";

                 exit(1);

              }

              // if successful to close the file, do...

             else

               cout<<"\nThe "<<filename<<" file was closed successfully!\n";

       }

 }

Testing: Just rumble example.

istream& ignore(streamsize n = 1, int delimter = EOF);

 // istream ignore()

#include <iostream>

using namespace std;

 

int main ()

{

  char firstword, secondword;

 

  cout<<"Enter your first and last names: ";

  firstword = cin.get();

  cin.ignore(30,' ');

  secondword = cin.get();

  cout<<"The initials letters are: "<<firstword<<secondword<<endl;

 return 0;

}

 

Output:

 

C++ file I/O ignore()

// reading from available file content

// then writing the content to another file.

// Firstly, create a file for reading (can include path)

// let says "C:\sampleread.txt", at root on C drive.

// Type some text in the file and save it, then executes this program.

#include <iostream>

#include <fstream>

usingnamespace std;

 

// function definition, to open file for reading...

void openinfile(ifstream &infile)

{

    char filename[100];

     cout<<"Enter the file name: ";

    // enter the filename that you have created (can include path).

     // From the comment above you have to enter "C:\sampleread.txt" without the double quotes.

     cin>>filename;

     infile.open(filename);

}

 

void main(void)

{

    // declare the input file stream

     ifstream inputfile;

    // declare the output file stream

     ofstream outputfile;

    char chs;

    // function call for opening file for reading...

     openinfile(inputfile);

    // create, if does not exist and open it for writing

     outputfile.open("C:\\samplewrite.txt");

    // test until the end of file

    while (!inputfile.eof())

     {

           // read character until end of file

            inputfile.get(chs);

           if (!inputfile.eof())

            {

               // output character by character (byte) on screen, standard output

                cout<<chs;

               // write to output file, samplewrite.txt

                outputfile<<chs;

            }

     }

     cout<<"\nReading and writing file is completed!"<<endl;

    // close the input file stream

     inputfile.close();

    // close the output file stream

     outputfile.close();

}

 

Output:

 

 

// a simple processing data from external file.

// Read the data in sequential mode, do some

// calculation and display to the standard output.

// Firstly create file testfileio.txt in the current

// working directory and type some int data in it...

#include <iostream>

#include <fstream>

using namespace std;

 

int main(void)

{

        char filename[ ] = "testfileio.txt";

        ifstream inputfile;

       

        // opening input file for reading

        inputfile.open(filename, ios::in);

        // test if fail to open the file, do...

        // error handling for file opening

        if(inputfile.fail())

        {

                cout<<"Opening file "<<filename<<" for reading\n";

                cout<<"------------------------------------------\n";

                cout<<"The file could not be opened!\n";

                cout<<"Possible errors:\n";

                cout<<"1.  The file does not exist.\n";

                cout<<"2.  The path was not found.\n";

                exit(1);   // just exit

               // 0-normal, non zero - some error

        }

        // if successful, do the following...

        else

        {

            cout<<"The "<<filename<<" file was opened successfully!\n";

            // declare some variables for simple calculation

            float price, total = 0;

            int count = 0;

            cout<<"Reading data and do some calculation\n\n";

            // read data from input stream...

            inputfile>>price;

           // test, if end of file not found, do the following...

            while(!inputfile.eof())

            {

                   // total = total + price

                   total += price;

                   count++;

                   cout<<"Item price # "<<count<<" is "<<price<<endl;

                   // re read the next item price within the loop

                   inputfile>>price;

        }

        cout<<"The total price for "<<count<<" items is: "<<total<<endl;

        cout<<"\n-------DONE-------\n"<<endl;

        // close the input file

        inputfile.close();

        // test closing file, if fail to close the file, do

        // a simple error handling for file closing

        if(inputfile.fail())

        {

            cout<<"The "<<filename<<" couldn't be closed!\n";

            exit(1);

        }

       // if fail, do....

        else

            cout<<"The "<<filename<<" file closed successfully!\n";

        return 0;

        }

}

 

[bodo@bakawali ~]$ g++ fileio.cpp -o fileio

[bodo@bakawali ~]$ ./fileio

 

The testfileio.txt file was opened successfully!

Reading data and do some calculation

 

Item price # 1 is 1.22

Item price # 2 is 4.5

Item price # 3 is 12

Item price # 4 is 10.56

Item price # 5 is 23.11

Item price # 6 is 7.8

Item price # 7 is 54.2

Item price # 8 is 30

Item price # 9 is 9.5

Item price # 10 is 45.45

The total price for 10 items is: 198.34

 

-------DONE-------

 

The testfileio.txt couldn't be closed!

Creating a new visual c++ project

Selecting Win32 console mode application type

the Win32 application wizard

 

 

 

Selecting an empty win32 project

 

 

 

 

 

 

 

 

----------------------------------------------------------------------------------

 

Adding a new item to the project - a new empty source file

Adding an empty C++ file .cpp to the project

  #include <iostream>

#include <fstream>

using namespace std;

 

 void main(void)

 {

      char filename[100];

      ifstream inputfile;

     // prompting user for filename to be opened…

      cout<<"Enter the file name to be opened: ";

     

     // store in filename, an array without [ ] is a pointer to the first array’s element...

      cin>>filename;

     // opened the file for input...

      inputfile.open(filename, ios::in);

     // test if fail to open file for reading, do…

      if(inputfile.fail())

      {

              cout<<"Opening "<<filename<<" file for reading\n";

              cout<<"---------------------------------------\n";

              cout<<"The "<<filename<<" file could not be opened!\n";

              cout<<"Possible errors:\n";

              cout<<"1.  The file does not exist.\n";

              cout<<"2.  The path was not found.\n";

              exit(1);   // just exit

             // 0-normal, non zero - some error

       }

      // if successful opening file for reading, do…

       else

       {

              cout<<"The "<<filename<<" file was opened successfully!\n";

              cout<<"\nDo some file processing here...\n";

       }

      // close file for input…

       inputfile.close();

      // test if fail to close the file, do…

       if(inputfile.fail())

       {

              cout<<"\nThe file "<<filename<<" could not be closed!\n";

              exit(1);

       }

      // else, do…

       else

           cout<<"\nThe "<<filename<<" file was closed successfully!\n";

}

 

Typing or copy and paste the C++ source code to the editor

Building the project (or solution)

 

 

Running the program

A sample of console mode program output

 

tenouk fundamental of C++ object oriented tutorial

 

 

 

 

 

 

 

 

 

Further C++ file input/output reading:

 

  1. The source code for this Module is C++ File I/O source codes.

  2. Check the best selling C/C++, Object Oriented and pattern analysis books at Amazon.com.

  3. Visual C++ .NET programming tutorials.

 

 

 

 

 

|< C++ File I/O 1 | Main | C/C++ Storage Class - volatile, global, local, const, mutable etc >|Site Index |Download |


C++ File Input/Output:  Part 1 | Part 2