DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are...

25
DATA FILE HANDLING File: A file is a collection of data stored on a disk or on some other relatively permanent storage medium. A file's existence does not depend on a running program. Data Files can be of two types : Text File or Binary File Text File Binary File A text file is a file that stores information as a string of ASCII characters i.e. it stores all alphabets, digits and other special symbols as 1 byte per character. For example, the number 123.45 will take 6 bytes of storage in a text file for its six characters A Binary file stores information as a sequence of bytes in the same format as the data is held in memory i.e. it stores characters in 1 byte, integers in 2 bytes , float in 4 bytes and so on. For example, the number 123.45 will take only 4 bytes as taken by float in memory In text files, each line of text is terminated by EOL (End of Line) character/newline character. When this EOL character is read or written, certain internal translations take place i.e. the newline character \n is translated to carriage return \r( ASCII - 13) + line feed \f (ASCII- 10) In text file a special character known as EOF (End of File) (ASCII -26 ) is inserted after the last character in the file to mark the end of file. In binary files, no delimiters are used for a line and no translations occur here. Binary file consists of nothing but data, there is no special character in the binary files to mark the end of file. Text file are not appropriate for data processing applications and numerical calculations. Text files are in a human readable format and have the advantage of being edited by a word processor like notepad. Text file is portable Binary files are appropriate for data processing applications and numerical calculations. Binary files are not in a human readable format. Binary files are not portable because the internal representation of data depends upon the platform used.

Transcript of DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are...

Page 1: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

DATA FILE HANDLINGFile: A file is a collection of data stored on a disk or on some other relatively permanent storage medium. A file'sexistence does not depend on a running program. Data Files can be of two types : Text File or Binary File

Text File Binary File

A text file is a file that stores information as a string of ASCII characters i.e. it stores all alphabets, digits and other special symbols as 1 byte per character. For example, the number 123.45 will take 6 bytes of storage in a text file for its six characters

A Binary file stores information as a sequence of bytes in the same format as the data is held in memory i.e. it stores characters in 1 byte, integers in 2 bytes , float in 4 bytes and so on. For example, the number 123.45 will take only 4 bytes as taken by float in memory

In text files, each line of text is terminated by EOL (End of Line) character/newline character. When this EOL character is read or written, certain internal translations take place i.e. the newline character \n is translated to carriage return \r( ASCII - 13) + line feed \f (ASCII- 10) In text file a special character known as EOF (End of File) (ASCII -26 ) is inserted after the last character in the file to mark the end of file.

In binary files, no delimiters are used for a line and no translations occur here. Binary file consists of nothing but data, there is no special character in the binary files to mark the end of file.

Text file are not appropriate for data processing applications and numerical calculations. Text files are in a human readable formatand have the advantage of being edited by a word processor like notepad. Text file is portable

Binary files are appropriate for data processing applications and numerical calculations. Binary files are not in a human readable format. Binary files are not portable because the internal representation of data depends upon the platform used.

Page 2: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

INPUT AND OUTPUT STREAMSStreams, are sequence of bytes flowing in and out of the programs (just like water flowing through a pipe). All input and output operations is accomplished through the use of input streams and output streams.

Input Stream : It Reads data from an input source (such as keyboard or disk file) and hands it over to the running program. Input Stream can be created by declaring an object of the istream class

Output Stream : It Writes the data received from the running program to an output sink (such as monitor or disk file).Output Stream can be created by declaring an object of the ostream class

Page 3: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

STREAM CLASS HIERARCHY ios is the base class of all stream classes. istream class is derived from ios class. cin is the object of istream

class and provides an input stream attached to the keyboard.istream class defines the extraction operator (>>) which readsdata from keyboard and hands over to program variables

ostream class is derived from ios class. cout is the object ofostream class and provides an output stream attached to themonitor. ostream class defines the insertion operator (<<) whichwrites the data received from program variables on the monitor

iostream class has multiple inheritance from both istream andostream class

ifstream class is derived fro istream class and provides inputstream attached to a disk file.

ofstream class is derived from ostream class and provides inputstream attached to a disk file.

fstream class is derived from iostream provides both input/outputfrom a disk file

iostream.h header file contains definitions for ios, istream, ostream and iostream classes fstream.h header file contains definitions for ifstream, ofstream and fstream classesNote : Including the header file fstream.h in your program provides functionality of the file stream classes as well as all classes of iostream.h

Page 4: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

CREATING A STREAM AND ASSOCIATING A FILE

Method 1:

Opening file using constructor of the stream class

Method 2:

Opening file using open() method of the stream class

ofstream ofil ("sample.txt");//passes filename as argument to constructor of ofstream classto create an output stream ofil attached to file sample.txt

ofstream ofil; // create an output stream

ofil.open("sample.txt"); //associates the output stream ofil to file sample.txt

ofil.close(); //dissociate the output stream ofil from file sample.txt

ifstream ifil ("sample.txt");//passes filename as argument to constructor of ifstream classto create an input stream ifil attached to file sample.txt

ifstream ifil; //create an input stream

ifil.open("sample.txt"); //associates the input stream ifil to file sample.txt

ifil.close(); //dissociate the output stream ifil from file sample.txt

When scope of the stream object is over, the destructor of the stream class is automatically invoked which first closes the file and then destroys the stream object.

You need to explicitly use the close() method to dissociate the file from the stream object . The stream object exists even after closing the file and can be re-associated with another file. Stream object gets destroyed only when the scope of the object is over.

Page 5: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

FILE OPENING MODES

File Mode Meaning Example

ios::out Opens file for writing only. It automatically truncate the file to zero size erasing the prior contents and places the file pointer at the beginning of file. If the file does not exist , a new file is automatically created.

fstream fil;fil. open ("file.dat", ios::out );

ios::in Opens file for reading only. The prior contents of the file are retained and the file pointer is placed at the beginning of file. If the file does not exist input fails.

fstream fil;fil. open ("file.dat", ios::in);

ios::app Opens the file for writing but the prior contents of the file are retained and the file pointer is placed at the end of file. New data is appended to the end of file

fstream fil;fil. open ("file.dat", ios::app);

ios::ate It merely places the file pointer at the end of file upon original open, but the file pointer can be moved anywhere in the file for input/output operations, this mode is used along with other modes

fstream fil;fil. open ("file.dat", ios::in|ios::out|ios::ate);

ios::binary File opens in binary mode, By default the file is opened in text mode fstream fil;fil. open ("file.dat", ios::out | ios:: binary);

ios::nocreate Open fails if the file does not exist fstream fil;fil. open ("file.dat", ios::out | ios:: nocreate);

ios::noreplace Open fails if the file already exist fstream fil;fil. open ("file.dat", ios::out | ios:: noreplace);

ios::trunc Delete the contents of the file if it exist fstream fil;fil. open ("file.dat", ios::in|ios::out|ios::trunc);

A file must be opened before you can read from it or write to it. An object of ifstream class by default opens the file in input mode for readingonly, ofstream class object opens the file in output mode for writing only. However the fstream class object has the functionality of bothinput and output and you can specify the modes which you want to use. File modes can be combined using the bitwise operator OR (|).

Page 6: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

WORKING WITH BINARY FILES

write() read()

It is a member function of ostream (inherited by ofstream). The write() function is used to write a record (sequence of bytes) to the binary file. A record may be an array, structure or class.

It is a member function of istream (inherited by ifstream). The read() function is used to read a record (sequence of bytes) from the binary file. A record may be an array, structure or class.

Syntax:

streamobject . write ( (char*) &obj , sizeof ( obj ) ) ;

where, obj is the name of variable storing the contents to be written to file &obj gives the address of variable which is type casted to a character

pointer. This is required because compiler assumes the variable of character type.

Sizeof is an operator which computes and returns the size of any variable or datatype and represents the total number of bytes to be written

Syntax:

streamobject . read ( (char*) &obj , sizeof ( obj ) ) ;

where, obj is the name of variable storing the contents read from file &obj gives the address of variable which is type casted to a character

pointer. This is required because compiler assumes the variable of character type.

Sizeof is an operator which computes and returns the size of any variable or datatype and represents the total number of bytes to be written

Blocks of binary data can be written and read from binary files through stream functions write() and read(). These functions can write and read variables of all datatypes including structure variables and class objects

Page 7: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

STEPS TO PERFORM INPUT / OUTPUT ON A FILE

Step 1: Declare the required stream object.

Step 2: Connect the stream to a file ( Open the file in the desired mode)

Step 3: Perform (Input/output ) operations on the stream, via functions defined in the stream classStep 4: Disconnect (Dissociate) the stream from the file ( Close the file ).

Step 5: Free (Destroy) the stream object.

Operation on File File Mode

Creation of File fil . open( “ file.dat”, ios :: out | ios:: binary) ;

Display File fil . open( “ file.dat”, ios :: in | ios:: binary) ;

Appending Records fil . open( “ file.dat”, ios :: app | ios:: binary) ;

Searching Records fil . open( “ file.dat”, ios :: in | ios:: binary) ;

Modify Records fil . open( “ file.dat”, ios :: in | ios:: out | ios:: binary) ;

fstream fil ;

fil . close();

Page 8: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

void main(){clrscr();int ch;do {

cout<<"\n 1. Create a new data file";cout<<"\n 2. Append records in file";cout<<"\n 3. Display all records";cout<<"\n 4. Search a record by its record number";cout<<"\n 5. Search a record by its name";cout<<"\n 6. Search a record by its roll number";cout<<"\n 7. Modify the data file by its record number";cout<<"\n 8. Modify the data file by its roll number";cout<<"\n 9. Delete a record from a file";cout<<"\n 10. Sort the data file";cout<<"\n 11. Insert a record in the stored data file";cout<<"\n 12. Count the total number of records in the data file";cout<<"\n 13. Exit";cout<<"\n 14. Enter your choice ";cin>>ch;

Switch ( ch ){case 1 : createfile(); break;case 2 : append(); break;case 3 : display(); break;case 4 : searchbyrecno(); break;case 5 : searchbyname(); break;case 6 : searchbyrollno(); break;case 7 : modifybyrecno(); break;case 8 : modifybyrollno(); break;case 9 : deleterecord(); break;case 10 : sortfile(); break;case 11 : insertrecord(); break;case 12 : count();

}} while ( ch != 13 );

getch();}

DIFFERENT OPERATIONS ON A BINARY FILE

Page 9: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

BINARY DATA FILE

class : student structure : student

class student{ int rollno;

char name[20];int total;

public:void getdata(){ cout<<"enter roll no , name, total marks";

cin>>rollno;gets(name);cin>>total;

}void putdata(){ cout<<"\nroll no: "<<rollno;

cout<<"\tname: "<<name;cout<<"\ttotal marks: "<<total;

}char* retname() { return name ;}int retrollno() { return rollno ; }

};

struct student{ int rollno;

char name[20];int total;

};

Consider the following :

Page 10: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

CREATE FILE ( WRITE TO FILE)Writing class objects to file Writing structure variables to file

void createfile(){ fstream fil;

student s;char ch;fil.open("result.dat",ios::out|ios::binary);

do { s.getdata();fil.write( (char*)&s , sizeof(s) );cout<<"more records? press y or n ";cin>>ch;

} while ( ch != 'n‘ );fil.close();

}

void createfile(){ fstream fil;

student s;char ch;fil.open("result.dat",ios::out|ios::binary);

do { cout<<"enter roll no , name, total marks";cin>>s.rollno; gets(s.name); cin>>s.total;fil.write( (char*)&s , sizeof(s) );cout<<"more records? press y or n ";cin>>ch;

} while ( ch != 'n‘ );fil.close();

}

void appendfile(){ fstream fil;

student s;char ch;fil.open("result.dat", ios:: app |ios::binary);

do { s.getdata();fil.write( (char*)&s , sizeof(s) );cout<<"more records? press y or n ";cin>>ch;

} while ( ch != 'n‘ );fil.close();

}

void appendfile(){ fstream fil;

student s;char ch;fil.open("result.dat", ios:: app |ios::binary);

do { cout<<"enter roll no , name, total marks";cin>>s.rollno; gets(s.name); cin>>s.total;fil.write( (char*)&s , sizeof(s) );cout<<"more records? press y or n ";cin>>ch;

} while ( ch != 'n‘ );fil.close();

}

Page 11: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

DISPLAY FILE ( READ FILE )

Reading class objects from file Reading structure variables from file

void displayfile(){fstream fil;student s;fil.open ("result.dat", ios::in|ios::binary);while( fil.read( (char*)&s , sizeof(s) ) ){s.putdata();

} fil.close();}

void displayfile(){fstream fil;student s;fil.open ("result.dat", ios::in|ios::binary);while( fil.read( (char*)&s , sizeof(s) ) ){cout<<"\n roll no: "<<s.rollno;cout<<"\t name: "<<s.name;cout<<"\t total marks: "<<s.total;

} fil.close();}

Page 12: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

SEARCH A RECORDReading class objects from file Reading structure variables from file

void searchbyrollno(){ fstream fil;

student s; int rno; char flag = 'n';cout<<"enter the roll no you want to search for ";cin>>rno;fil.open("result.dat", ios::in | ios::binary);

while( fil.read ( (char*)&s , sizeof(s) ) ){ if(s.retrollno()==rno)

{ s.putdata(); flag = 'y'; break;}

} if (flag == 'n') cout << "record not found";fil.close();}

void searchbyrollno(){ fstream fil;

student s; int rno; char flag = 'n';cout<<"enter the roll no you want to search for ";cin>>rno;fil.open("result.dat", ios::in | ios::binary);

while( fil.read ( (char*)&s , sizeof(s) ) ){ if(s.rollno==rno)

{ cout<<s.rollno<<s.name<<s.total<<endl;flag = 'y'; break;

}} if (flag == 'n') cout << "record not found";fil.close();}

void searchbyname(){ fstream fil;

student s; char nm[20]; char flag = 'n';cout<<"enter the name you want to search for ";gets(nm);fil.open("result.dat", ios::in | ios::binary);

while( fil.read ( (char*)&s , sizeof(s) ) ){ if(strcmpi(s.retname(),nm)==0)

{ s.putdata(); flag = 'y'; break;}

}if (flag == 'n') cout << "record not found";fil.close();}

void searchbyname(){ fstream fil;

student s; char nm[20]; char flag = 'n';cout<<"enter the name you want to search for ";gets(nm);fil.open("result.dat", ios::in | ios::binary);

while( fil.read ( (char*)&s , sizeof(s) ) ){ if(strcmpi(s.name,nm)==0)

{ cout<<s.rollno<<s.name<<s.total<<endl;flag = 'y'; break;

}} if (flag == 'n') cout << "record not found";fil.close();}

Page 13: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

FILE POINTERS AND RANDOM ACCESS

Put Pointer ( For Writing /Output ) Get Pointer ( For Reading /Input )

Put pointer specifies where the next output or write operation will occur i.e. it tells the current position for writing

Get pointer specifies where the next input or read operation will occur i.e. it tells the current position for reading

tellp() : It is a member function of ostream (inherited by ofstream). It returns the current byte position of the put pointer from the beginning of the file

fstream fil;

long int position = fil . tellp();

tellg() : It is a member function of istream (inherited by ifstream). It returns the current byte position of the get pointer from the beginning of the file

fstream fil;

long int position = fil . tellg();

seekp() : It is a member function of ostream (inherited by ofstream). It is used to reposition the get pointer in the file.Syntax:

streamobject . seekp( offset , seek_dir ) ;where, offset is an integer and seek_dir is a reference point

(ios::beg , ios:: cur, ios:: end)Example :

fstream fil;

fil.seekp( 10 , ios:: beg);// places get pointer at 10 bytes from the beginning of file

fil.seekp( -20 , ios:: end); // places get pointer at 20 bytes backward from the end of file

fil.seekp( 5 , ios:: cur); // places get pointer at 5 bytes from the current position

fil.seekp( 30 ); // ios::beg is taken as the default reference point

seekg() : It is a member function of istream (inherited by ifstream). It is used to reposition the get pointer in the file.Syntax:

streamobject . seekg( offset , seek_dir ) ;where, offset is an integer and seek_dir is a reference point

(ios::beg , ios:: cur, ios:: end)Example :

fstream fil;

fil.seekg( 10 , ios:: beg); // places get pointer at 10 bytes from the beginning of file

fil.seekg( -20 , ios:: end);// places get pointer at 20 bytes backward from the end of file

fil.seekg( 5 , ios:: cur); // places get pointer at 5 bytes from the current position

fil.seekg( 30 );// ios::beg is taken as the default reference point

Page 14: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

SEARCH A RECORD

Reading class objects from file Reading structure variables from file

void searchbyrecno(){fstream fil;student s;int recno;cout<<"enter the record no you want to search for ";cin>>recno;

char flag = 'n';fil.open("result.dat", ios::in | ios::binary);fil.seekg ( sizeof(s)*(recno-1) , ios::beg);

if ( fil.read ( (char*)&s , sizeof(s) ) ){s.putdata();flag = 'y'; }

if (flag == 'n')cout << "record number not found";fil.close();}

void searchbyrecno(){fstream fil;student s;int recno;cout<<"enter the record no you want to search for ";cin>>recno;

char flag = 'n';

fil.open("result.dat", ios::in | ios::binary);fil.seekg ( sizeof(s)*(recno-1) , ios::beg );if ( fil.read ( (char*)&s , sizeof(s) ) ){

cout<<s.rollno<<s.name<<s.total<<endl;flag = 'y'; }

if (flag == 'n')cout << "record number not found";fil.close();}

1 Upanshu 1002 Vinamre 993 Raghav 754 Manan 60

24 Bytes 48 Bytes72 Bytes96 Bytes

Page 15: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

MODIFY A RECORDReading and overwriting class objects from file Reading and overwriting structure variables

void modifybyrollno(){ fstream fil;student s;int rno;cout<<"enter the roll no you want to modify ";cin>>rno;fil.open ("result.dat", ios::in | ios::out|ios::binary);while( fil.read((char*)&s,sizeof(s)) ){ if(s.retrollno()==rno)

{ fil.seekp ( fil.tellg() - sizeof(s) , ios::beg );s.getdata();fil.write ( (char*)&s , sizeof(s) );

} }fil.close();}

void modifybyrollno(){ fstream fil;student s;int rno;cout<<"enter the roll no you want to modify ";cin>>rno;fil.open ("result.dat", ios::in | ios::out|ios::binary);

while( fil.read((char*)&s,sizeof(s)) ){ if(s.rollno==rno)

{ fil.seekp ( fil.tellg() - sizeof(s) , ios::beg );cin>>s.rollno; gets(s.name); cin>>s.total;fil.write ( (char*)&s , sizeof(s) );

} }fil.close();}

void modifybyrecno(){ fstream fil;

student s;int recno;cout<<"enter the record number you want to modify ";cin>>recno;fil.open ("result.dat", ios::in | ios::out|ios::binary);fil.seekg ( sizeof(s)*(recno-1) , ios::beg );s.getdata();fil .write ((char*)&s , sizeof(s) );fil.close();

}

void modifybyrecno(){ fstream fil;

student s;int recno;cout<<"enter the record number you want to modify ";cin>>recno;

fil.open ("result.dat", ios::in | ios::out|ios::binary);fil.seekg( sizeof(s)*(recno-1) , ios::beg );cin>>s.rollno; gets(s.name); cin>>s.total;fil.write ( (char*)&s ,sizeof(s) );fil.close();

}

1 Upanshu 1002 Vinamre 993 Raghav 754 Manan 60

24 Bytes48 Bytes72 Bytes96 Bytes

Page 16: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

COUNT NUMBER OF RECORDS IN FILE

Reading class objects from file Reading structure variables from file

void count(){fstream fil;student s;fil.open("result.dat",ios::in|ios::binary);fil.seekg ( 0 , ios::end );long int end = fil.tellg();long int num = end / sizeof(s);cout<<"number of records in the data file "<<num;fil.close();}

void count(){fstream fil;student s;fil.open("result.dat",ios::in|ios::binary);fil.seekg ( 0 , ios::end );long int end = fil.tellg();long int num = end / sizeof(s);cout<<"number of records in the data file "<<num;fil.close();}

1 Upanshu 1002 Vinamre 993 Raghav 754 Manan 60

24 Bytes48 Bytes72 Bytes96 Bytes

Page 17: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

void deleterecord(){fstream fil1,fil2;student s;int rno;cout<<"enter roll no you want to delete ";cin>>rno;fil1.open("result.dat",ios::in|ios::binary);fil2.open("temp.dat",ios::out|ios::binary);while( fil1.read ( (char*)&s , sizeof(s)) ){if(s.retrollno()!=rno)fil2.write ( (char*)&s , sizeof(s) );}fil1.close();fil2.close();fil2.open("temp.dat",ios::in|ios::binary);fil1.open("result.dat",ios::out|ios::binary);while( fil2.read ( (char*)&s , sizeof(s)) ){ fil1.write ( (char*)&s , sizeof(s) ); }fil1.close();fil2.close();}

1 Upanshu 1002 Vinamre 993 Raghav 754 Manan 60

result.dat

1 Upanshu 1002 Vinamre 994 Manan 60

temp.dat

1 Upanshu 1002 Vinamre 994 Manan 60

result.dat

// copying all records to temp.dat except the record t o be deleted

// recreating result.dat from temp.dat

DELETE A RECORD

Page 18: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

SORT THE FILEvoid sort(){fstream fil;student s , arr[100],temp; int index=0;fil.open("result.dat",ios::in|ios::binary);while( fil.read ( (char*)&s , sizeof(s) ) ){arr[index]=s;index++;}fil.close();for(int i=0;i<index;i++){

for(int j=0;j<index-i-1;j++){if( arr[j].retrollno() > arr[j+1].retrollno() ){ temp=arr[j];

arr[j]=arr[j+1];arr[j+1]=temp;

}}

}fil.open("result.dat",ios::out|ios::binary);

for(int x=0;x<index;x++){ fil.write ( (char*)&arr[x] , sizeof(s) ); }fil.close();}

// copying records from file to array

// bubble sorting the array

// recreating result.dat from sorted array

Page 19: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

INSERT NEW RECORD IN SORTED FILE

void insertrecord(){ fstream fil1, fil2; student s; int pos=0, no;cout<<"enter the roll no you want to insert "; cin>>no;fil1.open("result.dat",ios::in|ios::binary);

while( fil1.read ( (char*)&s , sizeof(s)) ) { if(no>s.retrollno())

pos++;} fil1.close();

fil1.open("result.dat",ios::in|ios::binary); fil2.open("temp.dat",ios::out|ios::binary);

for(int i=1;i<=pos;i++){ fil1.read ( (char*)&s , sizeof(s) );

fil2.write ( (char*)&s , sizeof(s) ); }

cout<<"enter new record "<<endl;s.getdata();fil2.write ( (char*)&s , sizeof(s) );

while( fil1.read ( (char*)&s , sizeof(s)) ){ fil2.write ( (char*)&s , sizeof(s) ); }

fil1.close(); fil2.close();fil1.open("result.dat",ios::out|ios::binary);fil2.open("temp.dat",ios::in|ios::binary);

while( fil2.read ( (char*)&s , sizeof(s)) ){ fil1.write ( (char*)&s , sizeof(s) ); }

fil1.close(); fil2.close();}

// to find position

// copying prior records to temp.dat

// write new record in temp.dat

// copying remaining records to temp.dat

// recreating result.dat from temp.dat

Page 20: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

WORKING WITH TEXT FILESInput Stream Functions (ifstream class) Output Stream Functions (ofstream class)

get() : It is inherited from istream class into ifstream class. It isused to read a single byte of data i.e. a single character from theassociated stream even if it is a whitespace character like a space,tab or newline and store it into a memory variable.

ifstream ifil ("story.txt"); char ch;ifil.get(ch);

put() : It is inherited from ostream class into ofstream class. It isused to write a single character to the associated stream even if itis a whitespace character like a space, tab or newline.

ofstream ofil ("story.txt"); char ch; cin>> ch;ofil.put(ch);

getline() : It is inherited from istream class into ifstream class. It isused to read specified number of characters from Input stream orall the characters until the delimiting character is reachedwhichever occurs earlier. It does not leave the delimitingcharacter in the input stream and extract it also. But it does notappend it to input, instead it appends a null character '\0' to inputconverting it to a string. If the delimiting character is not specifiedthen by default '\n‘ is the delimiting character.

ifstream ifil ( "story.txt" ); char sen[80];ifil.getline( sen , 80 , '.' );

Extraction operator (>>) : It skips over whitespace and terminates input (reading ) when a whitespace character is encountered.

ifstream ifil ( "story.txt" ); char word[40];Ifil >> word ;

Insertion operator (<<) : It can be used to write characters, strings or variables of any datatype to the associated stream

ofstream ofil ("story.txt"); char sen[80]; gets(sen);ofil << sen ;

Page 21: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

USING INSERTION (<<) AND EXTRACTION (>>) OPERATORS

Writing to file

void createfile(){char ch, name[20];int marks;ofstream ofil; ofil.open("student.dat"); //output stream connected to student.dat

do {cout<<"enter the name of student and his marks\n";cin >> name >> marks; // extracting from keyboard

ofil << name << "\t" << marks << "\n"; // inserting in disk file

cout<<"do you want to enter more records? enter y or n ";cin>>ch;} while( ch=='y'||ch=='Y‘ );

ofil.close();}

Reading from file

void displayfile(){

char name[20];int marks;ifstream ifil;ifil.open("student.dat");//input stream connected to student.dat

while( ifil >> name >> marks ) // extracting from disk file

{cout << name << "\t"<< marks << "\n"; // inserting on monitor

}ifil.close();

}

Extraction operator skips over whitespace and terminates input (reading ) when a whitespace character is encountered. Therefore, when writing data on a file "\t" is inserted to separate name and marks. Also "\n" is used to separate next record (name) and so on .

Page 22: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

DETECTING END OF TEXT FILE

Method 1 : Using eof() function Method 2: Without eof() function

void displayfile(){

char ch ;ifstream ifil;ifil.open("story.txt"); //input stream connected to student.dat

while ( ! ifil.eof() ){

ifil.get(ch) ;cout<<ch;

}ifil.close();

}

void displayfile(){

char ch ;ifstream ifil;ifil.open("story.txt"); //input stream connected to student.dat

while ( ifil.get(ch) ){cout<<ch;}

ifil.close();}

eof() function returns a true or non-zero when end of file is reached otherwise it returns false or zero. Thus on reaching the end of file the condition becomes !true i.e. false causing the loop to stop

get() function reads a single character and returns the address of the character read. On reaching the end of file it returns null (false ) causing the loop to stop

Page 23: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

DIFFERENT WAYS TO READ A TEXT FILECharacter by Character Word by Word

(separated by any whitespace character)

Sentence by Sentence(separated by any newline character)

void readfile(){ char ch ;ifstream ifil;ifil.open("story.txt"); while ( ! ifil.eof() ){ ifil.get( ch ) ; //reads whitespace characters

cout << ch;}ifil.close();}

void readfile(){ char word[80] ;ifstream ifil;ifil.open("story.txt"); while ( ! ifil.eof() ){ ifil >> word; // extraction stops at whitespace

cout << word <<" " ;}ifil.close();}

void readfile(){ char sentence[80] ;

ifstream ifil;ifil.open("story.txt"); while ( ! ifil.eof() ){ ifil.getline( sentence , 80 , ' \n ‘ ) ;

cout << sentence <<"\n ";}ifil.close();

}

CREATING A TEXT FILEvoid createfile(){ char sen[80]; char ch;

ofstream ofil;ofil.open ("lines.txt");do { cout<<"enter a line\n";

gets(sen);ofil<<sen<<"\n";cout<<"more lines? press y or n ";cin>>ch;

} while(ch!='n');ofil.close();

}

Page 24: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

SOME ALTERNATIVES

Character by Character Word by Word Sentence by Sentence

void readfile(){ char ch ;ifstream ifil;ifil.open("story.txt"); while ( ! ifil.eof() ){ ifil >>ch; /* It will read only printable characters and not read any whitespace character like space , tab or newline */

cout << ch;}ifil.close();}

void readfile(){ char word[80] ;ifstream ifil;ifil.open("story.txt"); while ( ! ifil.eof() ){ ifil .getline(word,80, ' ' )/* It will extract one word until a space is encountered but it

will not extract the last word in the sentence which is not followed by space and instead with a dot or newline character until the next space */

cout << word <<" " ;}ifil.close();}

void readfile(){ char sentence[80] ;

ifstream ifil;ifil.open("story.txt"); while ( ! ifil.eof() ){ ifil.getline( sentence , 80 , ' .‘ ) ;

/* It will extract the entire sentence until a dot is encountered even if the sentence spans multiple lines of text */

cout << sentence <<"\n ";}ifil.close();

}

Sample : Text File

Page 25: DATA FILE HANDLING - WordPress.com · 2020. 1. 14. · INPUT AND OUTPUT STREAMS Streams, are sequence of bytes flowing in and out of the programs (just like water flowing through

#include<fstream.h>#include<conio.h>#include<ctype.h>#include<stdio.h>

void createfile(){char note[100];ofstream ofil;ofil.open("notes.txt");cout<<"enter a note\n";gets(note);ofil<<note;ofil.close();}

void display(){ifstream ifil;ifil.open("notes.txt");int count=0, words=0, num=0;char ch;while ( ! ifil.eof() ){ifil.get(ch); // reads all characters including whitespace characters

count++;if(ch==' ' || ch=='.' )words++;

else if(isdigit(ch))num++;

}cout<<"\ntotal number of characters in the file: "<<count;cout<<"\ntotal number of numeric characters in the file: "<<num;cout<<"\ntotal number of words in the file: "<<words;cout<<"\ntotal average word size of the file: "<<(count-words)/words;}

void main(){clrscr();createfile();display();getch();}

Ques: Write a program to create a text file NOTES.TXT and display the following data on the screen:a) Total number of characters in the file.b) Total number of numeric characters in the file.c) Total number of words in the file where each word is separated by a single space.d) Total average word size of the file.