NIOS Computer Science: Chapter 16 – Files Part 4

Download PDF of This Page (Size: 378K)

Table shows Function for Manipulation for File Pointer

Table Shows Function for Manipulation for File Pointer

Table shows Function for Manipulation for File Pointer

4. The tellg ( ) and tellp ( ) function

The tellg ( ) function gives the position of get pointer in terms of number of bytes. Similarly, tellp ( ) function gives the position of put pointer in terms of bytes.

Example 2

ifstream infile;

infile . open ( “ABC”, ios ::ate);

int B = infile . tellg ( );

On execution of the above statements, the input pointer is moved to the end of the file and B gives the number of bytes in the file.

5. Write ( ) and read ( ) functions

The functions write ( ) and read ( ) have two parameters: address of the variable, size of the variable. The address of the variable must be cast to the type char*. The general format is:

infile.read( (char*) & v, sizeof v);

outfile.write( (char*) & v, sizeof v);

Where v is the variable.

6. Close ( ) function

The file should be closed at the end if it is opened either through constructor or open ( ) function. The General format is stream_object.close( );

The following example works with class object and does the following operations:

  • Create a data file

  • Display a data file

  • Adding a new record

  • Modify the existing record

Example 3

# include <fstream.h>

class student

{

char name [30];

int rn;

public:

void getdata ( );

void putdata ( );

};

void student : : getdata ( )

{

cout <<“Enter student name”;

cin >> name;

cout << “Enter roll number”;

cin >> rn;

}

void student :: putdata ( )

{

cout << “Student name” << name << “\n”;

cout << “Student roll number” << rn << “\n”;

}

void main ( )

{

fstream file;

file . open ( “ABC”, ios::in l ios::out l ios::binary);

student st;

/ / create a data file

int i, n;

cout << “How many record to enter”;

cin >> n;

for (i = 1; i < = n, i ++ )

{

st.getdata( );

file.write((char*) & st, sizeof st);

}

/ / Display a data file

file.seekg(0, ios::beg);

while (file.read ((char*) & st, sizeof st))

{

st.putdata ( );

}

file.clear ( ) / / To make the end of file mark false

/ / To append record

st.getdata ( );

file.write ((char*) & st, sizeof st);

/ / To modify a record

file.clear ( );

cout << “Enter record number”;

cin >> n;

file.seekp ((n - 1)* sizeof st, ios::beg);

st.getdata ( );

file.write ((char*) & st, sizeof st);

/ / To close a file

file.close ( );