File Handling in c++,The Iostream Library,Reading and writing I/O files

As can be seen, there are build in  class’s  present in  C++ for accessing the input-output stream

The Iostream Library

Class(ios) is the root of the iostream class hierarchy, for instant iostream  class contain’s features  that will be common for all streams

To clarify, stream means the flow of data

Ex: output stream helps the flow of data to the screen,

Ex: the input stream helps to receive a flow of data from a keyboard

Rendered by QuickLaTeX.com

Reading and writing I/O files with streams

As I said, to carry I/O task in C++ (Reading/Writing) we need certain set of classes as shown below

ClassExtracted fromUse
ofstreamfstreambase, ostreamoutput a file
ifstreamfstreambase, istreaminsert input to a file
fstreamfstreambase,iostreamboth output and input

The ofstream,ifstream and fstream classes are included in the declaration of file fstream.h

Cin >> is used as an insertion operator for writing

Cout<< is used as an extraction operator for reading

declaration

ifstream  obj1   //declares an object of type ifstream
ofstream  obj2  //declares an object of type ofstream

File opening

To open a file in C++, we should define an object of type ofstream class, for instance, consider the below statement

Ofstream obj("Demo.txt");

At times, you may not know the name of the ofstream object when it is created so, in that case, we first create an object and then call ofstream::open() function for file opening, consider the below statement

Ofstream obj;
Obj.open("Demo.txt");

Program to read and write a .txt file

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    // create a file called demo.txt and  define object name as obj
    ofstream obj("Demo2.txt");
    char ch ='A';
    int i =99;
    double d =786.14;
    char str[]="hi there i am anees";
    //insert data into demo.txt
    obj<<ch<<endl<<i<<endl<<d<<endl<<str;
    obj.close();
    //build an object1 of istream class
    ifstream obj1("Demo2.txt");
    //reading data
    obj1>>ch>>i>>d>>str;
    //sent data to display
    cout<<ch<<endl<<i<<endl<<d<<endl<<str;
}

output

A
99
786.14
hi

Using the getline() function

As has been noted the above program not able to print the full string “hi there i am anees” at this instant, we can solve this limitation by using getline() function

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    //// create a file called demo.txt and  define object name as obj
    ofstream obj("Demo7.txt");
    char ch ='A';
    int i =99;
    double d =786.14;
    char str[100]="hi there i am anees";
    //insert data into demo.txt
    obj<<ch<<endl<<i<<endl<<d<<endl<<str;
    obj.close();
    //build an object1 of istream class
    ifstream obj1("Demo7.txt");
    // Iterate till end of file is not encountered
    while(!obj1.eof())
    {
        obj1.getline(str,100);
        cout<<endl<<str;
    }
}

output

A
99
786.14
hi there i am anees

File opening modes

There are  different mode’s available for a stream object to open

Rendered by QuickLaTeX.com

Class  default mode
ifstream   ios::in
ofstream ios::out
fstreamios::in|ios::out

Prototype

Ofstream obj("filename", mode);

Example

ofstream obj("Demo.txt",ios::out);
Ofstream obj("Demo.txt",ios::app);

Apply both input and output mode on the binary file simultaneously

fstream obj;
Obj.open(filename,ios::in|ios::out|ios::binary);

as can seen, the vertical bars(|)  between the flags make the flags to logically merge into a single integer

Member types inherited from istream and ios_base

seekdir
sentry
openmode
iostate
fmtflags
init
failure
event_callback
event

public member functions

open
close
(constructor)
Is_open
Rdbuf
Swap(c++ 11)
Operator=(c++11)

public member function’s from istream

peak
ignore
getline
get
gcount
>>operator
read
readsome
putback
sync
seekg
tellg
unget

Member function :: gcount

count the number of character’s in a string

#include <iostream>
using namespace std;
int main () {
  char str[20];
  cout << "Please, enter a word: ";
  cin.getline(str,20);
  cout <<cin.gcount() << " characters read: "  << '\n';
  return 0;
}

Output

Please, enter a word: welcome
8 characters read:

Seekg member function

With seekg function, you can get or seek an arbitrary position inside a file

Syntax

1	Seekg(pos);
2	Seekg(bytes,  reference_point)

3 reference points

ios:: to move from beginning

ios:: to move from current postion

ios::to move from the end

sign(+)  –> to move forward

sign(-)   –>to move backward

examples

obj.seekg(3, ios::beg) —>  to move file pointer  from 3th position

obj.seekg(-5, ios::cur) —> move filepointer from current location to the backward direction

obj.seekg(-4, ios::end)—> move file pointer from backward direction

#include <iostream>
#include <fstream>
using namespace std;
int main () {
  ifstream obj ("x.txt", ios::binary);
  if (obj) {
    // get length of file:
    obj.seekg (0, obj.end);
    int length = obj.tellg();
    obj.seekg (3, obj.beg);
    // allocate memory:
    char * buffer = new char [length];
    // read data
    obj.read (buffer,length);
    obj.close();
    // print content:
    cout.write (buffer,length);
    delete[] buffer;
  }
  return 0;
}

Input

You are welcome

output

are welcome

tellg() member function

tell us the current location of the file pointer

Read and write member function

Read member function  is something  similar like scanf in C, to read a file, a file has to be available in the same project folder where the main() program is exist

Write member function is also something similar like printf in C

Syntax for write member function

write(char* s, stream_size);

Syntax for read member function

read(char* s,  stream_size);

#include <fstream>
#include <iostream>
using namespace std;
int main () {
  ifstream infile_obj ("in_file.txt",ios::in | ios::binary);
  ofstream outfile_obj ("out_file.txt", ios::out | ios::binary);
  // get size of file
  infile_obj.seekg (0,infile_obj.end);
  long size = infile_obj.tellg();
  infile_obj.seekg (0);
  // allocate memory 
  char* buffer = new char[size];
  // read content of infile_obj
  infile_obj.read (buffer,size);
  // write to outfile_obj
  outfile_obj.write (buffer,size);
  // delete dynamically-allocated memory
  delete[] buffer;
  outfile_obj.close();
  infile_obj.close();
  return 0;
}

Mohammed Anees

Hey there, welcome to aneescraftsmanship I am Mohammed Anees an independent developer/blogger. I like to share and discuss the craft with others plus the things which I have learned because I believe that through discussion and sharing a new world opens up

Leave a Reply

Your email address will not be published.