Monday, 6 May 2013

Functions in file handling and examples:


List of Important functions to handle file  :

open()
This function is member of ifstream as well as ofstream class. This function is used to open file in a particular mode. File modes and functioning of open() function is already discussed in this chapter.

Syntax
File_object.open( file name, file mode);

close()

When we are finished with our input and output operations on a file we shall close it so that its resources become available again. In order to do that we have to call the stream's member function close(). This member function takes no parameters, and what it does is to flush the associated buffers and close the file:

Syntax
file_object.close();

get()

get() function is defined in class istream.

There are several version of get() defined in istream class and derived in ifstream.
1) int get();

Example: 
#include<iostream>
#include<conio.h>
#include<fstream>
using namespace std;
int main()
{
    ifstream fin;
    fin.open("example.txt",ios::in);
    while(!fin.eof())
      cout<<fin.get();
    fin.close(); 
    getch();
}

If file example.txt contains integer values get function read one integer at a time and returns the same. If file contains text, get function returns its corresponding ASCII code.
Since in above program file example.txt has opened in text mode (as we do not mention binary mode) it is a good idea to replace statement cout<<fin.get(); by cout<<(char)fin.get();. It converts ASCII code into corresponding character.

2) istream& get(char&);

Example:
#include<iostream>
#include<conio.h>
#include<fstream>
using namespace std;
int main()
{
    ifstream fin;
    char ch;
    fin.open("example.txt",ios::in);
    fin.get(ch);
    while(!fin.eof())
    {
      cout<<ch;       
      fin.get(ch);
    }
    fin.close(); 
    getch();
}
This time get function is used to take character from input stream and store in char variable.

3) istream& get(char *s, streamsize n, char delim);

Example:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    char str[10];
      
    cin.get(str,10,'\n');
    cout<<str;
    getch();
}
This function inputs characters till ‘\n’ appears of 10 characters.

getline()
 
istream& getline (char* s, streamsize n, char delim );

Extracts characters from the input sequence and stores them as a c-string into the array beginning at s.
Characters are extracted until either (n - 1) characters have been extracted or the delimiting character is found (which is delim if this parameter is specified, or '\n' otherwise).

Example:
 
#include <iostream>
using namespace std;
 
int main () {
  char name[256], title[256];
 
  cout << "Enter your name: ";
  cin.getline (name,256);
 
  cout << "Enter your favourite movie: ";
  cin.getline (title,256);
 
  cout << name << "'s favourite movie is " << title;
}

read()
 
istream& read ( char* s, streamsize n );

This function is used to read data from input stream.
You can use it to read data input from keyboard or file.

Example: Input data from keyboard

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    char str[10];
   
    cin.read(str,5);
    cout<<str;
    getch();
}

Here, read function is used to input 5 characters form keyboard and store them to char array str.

Example : Input data from file

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

In the above program first we calculate length of the file. This is done by using function seekg() which is used to set file pointer (will be discussed in detail later in this chapter).
tellg()  tells the length of file from beginning to current position in the file point to by file pointer.

Our next job is to allocate memory using keyword new equal to the size of file.
Lastly, output data with cout.

write()

Syntax
ostream& write ( const char* s , streamsize n );

Writes the block of data pointed by s, with a size of n characters, into the output buffer. The characters are written sequentially until n have been written.


tellg()

This function is defined in istream class
Returns the absolute position of the get pointer.
Get pointer is a pointer to file.
The get pointer determines the next location in the input sequence to be read by the next input operation.


tellp()

This function is defined in ostream class
Returns the absolute position of the put pointer.
put pointer is a pointer to file.
The put pointer determines the location in the output sequence where the next output operation is going to take place.

Example :
#include <fstream>
#include <conio.h>
using namespace std;
 
int main () 
{
  long int pos;
 
  ofstream fout;
  fout.open ("example.txt");
 
  fout.write ("This is an apple",16);
  pos=fout.tellp();
  fout.seekp (pos-7);
  fout.write (" sam",4);
 
  fout.close();
  getch();
  
}


seekg()

syntax
istream& seekg ( streampos pos );
Sets the position of the get pointer.
The get pointer determines the next location to be read in the source associated to the stream.



Pos could be value returned by tellg()
Another version of seekg() is

istream& seekg ( streamoff off, ios_base::seekdir dir );
Integral value of type streamoff representing the offset to be applied relative to an absolute position specified in the dir parameter.
Seeking direction. It is an object of type ios_base::seekdir that specifies an absolute position from where the offset parameter off is applied. It can take any of the following member constant values:
ios_base::beg           beginning of the stream buffer
ios_base::curcurrent           position in the stream buffer
ios_base::end           end of the stream buffer


seekp()
Just like seekg(),  seekp() used to set position of put pointer
Syntax
ostream& seekp ( streampos pos );
ostream& seekp ( streamoff off, ios_base::seekdir dir );
 
Sets the position of the put pointer.



The put pointer determines the location in the output sequence where the next output operation is going to take place.
 Rest is same like seekg()

eof()

It is defined in ios class
It is end of file (eof)
The function returns 1 if the eofbit stream's error flag has been set by a previous i/o operation. This flag is set by all standard input operations when the End Of File is reached in the sequence associated with the stream. Otherwise it returns 0.

No comments:

Post a Comment