VINAY ALEXANDER PGT(CS) KV,SECL,JHAGRAKHAND. FILE:A file itself is a bunch of bytes stored on some...

Preview:

Citation preview

VINAY ALEXANDERPGT(CS)

KV ,SECL,JHAGRAKHAND

FILE:A file itself is a bunch of bytes stored on some storage device like tape, or magnetic disk etc.

STREAM: A stream is a sequence of bytes. 1.The stream is a general name given to a

flow of data at lowest level( at the lowest level, data is just the binary data without any notion of data type).

2. The stream that supplies data to the program is known as input stream. it reads the data from the file and hands it over to the program. the stream that received data from the program is known as output stream.it writes the received data to the file.

=>Disk File

Program

Output

streamstream

Input

filebuf : It sets the file buffers to read & write. It contains close( ) & open( ) functions.

fstreambase : This is the base class for fstream, ifstream, ofstream classes. open( ) close( )

ifstream : input file stream class. It provide input operation for file. It inherit get( ), getline( ), read( ) and function supporting random access (seekg( ) and tellp( )) from istream class defined inside iostream.h

ofstream : Output file stram class. It inherit put( ) and write( ) long with function supporting random access (seekp( ) and tellp( )) from ostream class defined class inside iostream.h

fstream :It is a predefines a set of operations for handling file related input and output.

it is an I/O file stream class. It inherits all function from istream and ostream classes through iostream class defined inside iostream.h.

Files are required for storing the data and information permanently. the data files can be stored in two way.

1. Text file : A text file stores information in ASCII characters. Each line terminated by EOL ( end of line). In text files some internal translations take place when this EOL character is read or written.

2. Binary file : It stores information in the same format in which the information is held in memory. No delimiter for line. no translation occurs. It is faster and easier for a program read and write.

In C++, there are three types of Stream: ifstream, ofstream & fstream .Opening of files can be achieved in two ways:1.Using Constructor:2.Using the function open( )

=>Using Constructor: To open a file , Datafile , as input file, we shall create a file stream object of input type. i.e. ifstream type:

ifstream input_file(“DataFile”); // create input object name as input_file

char ch;input_file>>ch;float amt;input_file>>amt;

ofstream output_file(“DataFile”); ”); // create output object name as output_file

input_file.close( ); // close input connection to fileoutput_file.close( ); // close output connection to file

ifstream filin; // create an input streamfilin.open(“master.dat”);//associate filin stream with file master.datfilin.close( );=>The Concept of file Modes: It describes how a file is to be used. To read from it ,to write to it, to append it and so on.=> In open( ) method , to provide the second argument as a file mode.the file mode is of type int.

stream_object.open(“filename”, (filemode));

S.No Constant Meaning Stream Type

I ios::in : open file in read mode, ifstream

ii ios::out : It open s file for writingi.e.,in output mode. ios::trunc

ofstream

iii ios::ate : seeks the to end of file upon opening of the file.

Ofstreamifstream

iv ios::app : appended to the end ofstream

V ios::trunc : pre-existing file destroyed and open file with zero length

ofstream

vi ios::nocreate

: not create a new file when open ( ) fail,

ofstream

vii ios::noreplace

: open( ) fail when file exists,

ofstream

viii ios::binary : Open a file in binary mode. By default it is text mode

ofstream, ifstream

Both ios::ate and ios::app place you at end of the file just opened. The ios::app mode allowes you to add data to the end of the file only, while the ios::ate mode lets you write data anywhere in the file, even over old data.=>The fstream class does not provide a mode by default and ,one must specify the mode explicitly when using an object of fstream class.

ofstream fout;

fout.open(“data.dat”, ios::binary | ios:app);

=> Closing a File: A file is closed by disconnecting it with the stream it is associated with.=> The function close( ) flushes the buffer before terminating the connection of the file with the stream.

fout.close( );

There are five steps to use file in your C++ program are:

1. Determine the type of link required.2. Declare a stream for the desired type

of link.3. Attach the desired file to the stream.4. Now process as required.5. Close the file-link with stream.

1. Determine the type of link required.

(i) File to memory: input purpose(Into the Memory) (ii) Memory to File: output purpose(OUT FROM the Memory)(iii)file-to-Memory/Memory-to-file:

input/output purpose

2. Declare a stream for the desired type of link.File to memory ifstream finMemory to File ofstream foutBoth fstream finout

ifstream fi; // stream name here is fiofstream fo; // stream name here is fofstream fio; // stream name here is fio

3. Attach the desired file to the stream.

ifstream fin(“data.dat”); //using constructor

Orfin.open(“data.dat”, ios::in); //using

open( )

ofstream fout(“oput.txt”);Orfout.open(“oput.txt”, ios::out);

fstream finout(“Newfile.txt”);Orfinout.open(“Newfile.txt”, ios::in |

ios::out);

4. Now process as required for the given problem.//get rollnumbers and marks of the students of a class and

store these details //into a file called marks.dat.#include<fstream.h>void main( ){ofstream fout;fout.open(“mark.dat”, ios::out);char ans=‘y’;int rollno;while(ans==‘y’ || ans==‘Y’) {

cout<<“\nEnter roll no : “;cin>>rollno;fout<<rollno;cout<<“\n Want to enter more? :”;cin>>ans;

}fout.close( );}

5.Close the file-link with stream.fin.close( );fout.close( );

#include<fstream.h>#include<conio.h>void main(){clrscr();ofstream fout("student");char name[30],ch;float marks=0.0;for(int i=0;i<5;i++){cout<<"students"<<(i+1)<<":\t Name:";cin.get(name,30);cout<<"\tmarks:";cin>>marks;cin.get(ch);

fout<<name<<'\n'<<marks<<'\n';}fout.close();ifstream fin("student");fin.seekg(0);cout<<"\n";for(i=0;i<5;i++){fin.get(name,30);fin.get(ch);fin>>marks;fin.get(ch);cout<<"student name:"<<name;cout<<"\t marks:"<<marks<<"\n";}fin.close();getch();}

#include<fstream.h>void main( ){ofstream fout;fout.open(“mark.dat”,ios::out);int rollno;for(int i=0;i<5;i++) {

cout<<“\nEnter roll no : “;cin>>rollno;fout<<rollno<<“\n”;

}fout.close( );ifstream fin(“mark.dat”);fin.seekg(0);cout<<“\n”;for(i=0;i<5;i++){fin.get(rollno);fin>>rollno;cout<<rollno;}}

=> Changing the Behaviors of Stream

The default behaviour of ofstream type stream(ios::out) ,uopn opening a file is that it create the file if the file does’t yet exist and truncates the file(i.e., deletes its previous contents) , if the file already exists. if you want to change the default behaviour, then you specify the following file mode with open( ) function.

ios::app To retain the previous contents of the file and to append to the end of existing file contents, rather than truncating them.

Sequential I/O with Files:1.The get() function read a single

character from associated tream and puts that values in ch. It returns a reference to the stream.

(i) istream & get (char & ch);(ii) istream & get(char * buf, int num,

char delim=‘\n’) cin.get( line, 40,’$’);(iii) int get();2.The put() function writes the

value of ch to stream and returns a reference to the stream.

(i) ostream & put(char ch);

//program to display contents of a file using get() function.

#include<fstream.h>#include<conio.h>int main( ){ char ch;ifstream fin;ifstream fin(“marks.dat”, ios::in);if(!fin){cout<<“Can’t open”;return 1;}while(fin){fin.get(ch);cout<<ch;}fin.close( );return 0;}

The getline() function: It reads characters and puts them in the array pointed to by buf until either num characters have been read. and removes the delimiter new line character from the input stream.

Syntax:istream & getline(char *buf,int

num,char delim=‘\n’);

Reading and writing blocks of binary data is to use read() and write() function.

The Read() function reads sizeof(buf) bytes from the associated stream and puts them in the buffer pointed to by buf

istream & read((char *) &buf, int sizeof(buf));The write() function writes sizeof(buf) bytes to

the associated stream from the buffer pointed to by buf.

ostream & write((char *) &buf, int sizeof(buf));fin.read((char *) &savec, sizeof(customer));fout.write((char *) &savec, sizeof(customer));

//WAP to write and read a structure using write() and read() function using a binary file.

#include<fstream.h>#include<string.h>#include<conio.h>struct customer{ char name[51];

float balance; };void main( ){ customer savac; strcpy(savac.name, “tina”);savac balance=21310.5;ofstream fout;fout.open(“saving”,ios::out | ios::binary);if(!fout){ cout<<“can’t open” ; return 1;}fout.write((char *) &savac, sizeof(customer));fout.close( );ifstream fin;fin.open(“saving”,ios::in | ios:: binary);fin.read((char *) &savac, sizeof(customer));cout<<savac.name<<“ has the balance amount of Rs.”<<savac.balance<<“\

n”;fin.close( );}

=>Reading and writing class objects: The function read() and write can also be used for reading and writing class objects. these functions handle the entire structure of an object as a single unit. Only data members are written t the disk file and not the member functions.

//WAP for reading and writing class object.

#include<fstream.h>#include<string.h>#include<conio.h>class Student { char name[51]; char grade;

float marks; public: void getdata(void);Void display(void); };Void Student:: getdata(void)Char ch;

void main( ){ customer savac; strcpy(savac.name, “tina”);savac balance=21310.5;ofstream fout;fout.open(“saving”,ios::out | ios::binary);if(!fout){ cout<<“can’t open” ; return 1;}fout.write((char *) &savac, sizeof(customer));fout.close( );ifstream fin;fin.open(“saving”,ios::in | ios:: binary);fin.read((char *) &savac, sizeof(customer));cout<<savac.name<<“ has the balance amount of

Rs.”<<savac.balance<<“\n”;fin.close( );}

Detecting EOF: this function detect the end of the file is reached.

Prototypeint eof( );It returns nonzero when the end of the file has

been reached ,otherwise it returns zero. File pointers and random access:

Random access is achieved by manipulating seekg( ),seekp( ),tellg( ) and tellp( )function.

The seekg( ) and tellg( ) functions allow to set and examine the get_pointer, and seekp( ) and tellp( ) functions perform these operations on the put_pointer.

The seekg( ) and tellg( ) functions are for input stream (ifstream) and seekp( ) and tellp( ) functions are for output streams (ofstream)

Syntax:seekg() –istream & seekg(long); #1 - istream & seekg(long,seek_dir); #2seekp() –oftream & seekp(long); #1 - oftream & seekp(long,seek_dir); #2(seek_dir takes the definition enum

seek_dir{beg,cur,end } ;)tellg( )- long tellg( )tellp( )- long tellp( )

Basic operations on Binary Files: 1.Searching: There are two method to

search a record in Binary file.(a). With records implemented through

structures(b). With records implemented through

classes

//WAP to searching in a file that has records maintained through structure.#include<iostream.h>struct stu { int rollno;char name[25];char class[4];float marks; char grade;} s1;void main( ) {int rn;char found =‘n’;Ifstream fi(“stu.dat”,ios::in);cout<“”enter rollno to be search for:”;cin>>rn;While(!fin.eof( ) ){Fi.read((char *) &s1,sizeof(s1));If(s1.rollno==rn){Cout<<s1.name<“,rollno:”<<rn<<“has”<<s1.marks<<“% marks and

“<<s1.grade<<“grade”<<endl;Found=‘y’;Break;}}If(found==‘y’)Cout<<“Rollno not found in file”<<endl;Fin.close( );}

Appending data: To append data in a file , the file opened with the following two specifications;

(i). File is opened in output mode(ii). File is opened in ios::app mode.If file opened in ios::app mode, the

previous record /information is retained and new data gets appended to the file.

#include<fstream.h>Class stu{ int rollno; char name[25],class[4],grade; float marks;public: void getdata( ){ cout<< “RollNo”; cin>>rollno; cout<<“Name:”cin>>name;Cout<<“class”;cin>>class;Cout<<“marks”;cin>>grade;If(marks>=75) grade=‘A’;else If(marks>=60) grade=‘B’;else if(marks>=50) grade=‘C’;else if(marks>=40) grade=‘D’;else grade=‘F’;}Void putdata( ){ cout<<name<<rollno<<marks<<grade<<endli;}int getrno( ){ return rollno;}} s1;

void main( ){ ofstream fo(“stu.dat”,ios::app);Char ans=‘y’;While(ans==‘y’){S1.getdata( );Fo.write((char *) &s1,sizeof(s1));Cout<<“record added to the file \n”;Cout<<“enter more record\n”;Cin>.ans;}fo.close( );}

Inserting data in sorted File: To insert data in a sorted file. To follow the following steps.

1 Determining the appropriate position.2.Copy the records to prior to determined

position to a temporary file say temp.dat.3. Append the new record in the temporary

file temp.dat.4. Now append the rest of the records in

temporary file temp.dat.5. Delete file stu.dat by issuing command.

remove(“stu.dat”);6.Remove file temp.dat as follows :

rename(“temp.dat” ,”stu.dat”);

Deleting a Record :To delete record, following procedure is carried out :

1. Firstly, determine the position of the record to be deleted, by performing a search in the file.

2. Keep copying the records other than the record to be deleted in a temporary file say temp.dat.

3. Do not copy the record to be deleted to temporary file, temp.dat.

4. Copy rest of the records to temp.dat.5. Delete original file say stu.dat as :

remove(“stu.dat”);6. Rename temp.dat as stu.dat as : rename

(“temp.dat” ,”stu.dat”);

Modifying Data To modify a record, the file is opened in I/O

mode and an important step is performed that gives the beginning address of record being modified. After the record is modified in memory, the file pointer is once again placed at the beginning position of this record and then record is rewritten. Following code illustrates it :

class stu { ://same as before

void modify() ; } s1 ; //get new data here

fstream fio;fio.open (“stu.dat”, ios ;; in ! Ios ;; out),“Read rollno whose data is to be modified” ;

long pos ;while(! Fio.eg()){ pos = fio.tellg( ) ; //determine beginnig position of

record

fio.read((char *) & s1, sizeof(s1)) .if (s1.getrno( ) == rn) //this is the record to be

modified.

{ s1.Modify ( ) ; //get new data

fio.seekg(pos) ;//place file pointer at the beginning record position

fio.write((char *) & s1, sixeof (s1)) ; //now write modified record

}}

ERROR Handling during file I/O:Name Meaningeofbit -> 1 when end of file is encountered,

0 otherwiseeailbit -> 1 when a non-fatal I/O error has

occurred, 0 otherwisebadbit -> 1 when a fatal I/O error has

occurred, 0 otherwisegoodbit -> 0 value

Function Meaningint bad ( ) Return non zero value.if an

invalid operation is attemted or any unrecoverable error occurred.otherwise 0.

int eof() Return non zero value.if end of file is encountered while reading otherwise 0.

int fail( ) Return non zero when an input or output operation failed

int good( ) Return non zero if no error occurred this means ,alll the above functions are false.otherwise 0.

clear ( ) Reset the error state so that further operations can be attempted.

Recommended