Presentation is loading. Please wait.

Presentation is loading. Please wait.

VINAY ALEXANDER PGT(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.

Similar presentations


Presentation on theme: "VINAY ALEXANDER PGT(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."— Presentation transcript:

1 VINAY ALEXANDER PGT(CS) KV,SECL,JHAGRAKHAND

2 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 to known as output stram.it writes the received data to the file.

3 Disk File Program Output stream Input

4 filebuf : It sets the file buffers to read & write. close( ) & open( ) 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 ad 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.

5 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.

6 Opening of files can be achieved in two ways: 1.Using Constructor: 2.Using the function open( ) =>Using Constructor: 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 file output_file.close( ); // close output connection to file

7 ifstream filin; filin.open(“master.dat”); filin.close( );

8 S.NoConstantMeaningStream 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. Ofstream ifstream iv ios::app: appended to the endofstream 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

9 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. stream _object.open(“filename”,(filemode)); ofstream fout; fout.open(“data.dat”,ios::binary | ios:app); fout.close( );

10 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.

11 1. Determine the type of link required. (i) File to memory input (IN To the Memory) (ii) Memory to File output (OUT FROM the Memory) (iii)Both input/output

12 2. Declare a stream for the desired type of link. File to memoryifstream fin Memory to Fileofstream fout Bothfstream finout ifstream fi; // stream name here is fi ofstream fo; // stream name here is fo fstream fio; // stream name here is fio

13 3.Attach the desired file to the stream. ifstream fin(“data.dat”); //using constructor Or fin.open(“data.dat”, ios::in); //using open( ) ofstream fout(“oput.txt”); Or fout.open(“oput.txt”, ios::out); fstream finout(“Newfile.txt”); Or finout.open(“Newfile.txt”, ios::in | ios::out);

14 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 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<>ans; } fout.close( ); }

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

16 #include 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);

17 fout<>marks; fin.get(ch); cout<<"student name:"< { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/14/4377295/slides/slide_17.jpg", "name": "fout<>marks; fin.get(ch); cout<< student name: <>marks; fin.get(ch); cout<< student name: <

18 #include 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; cout< { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/14/4377295/slides/slide_18.jpg", "name": "#include 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; cout<>rollno; fout<>rollno; cout<

19 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);

20 //program to display contents of a file using get() function. #include 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< { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/14/4377295/slides/slide_20.jpg", "name": "//program to display contents of a file using get() function.", "description": "#include 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<

21 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. istream & getline(char *buf,int num,char delim=‘\n’);

22 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));

23 //WAP to write and read a structure using write() and read() function using a binary file. #include 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< { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/14/4377295/slides/slide_23.jpg", "name": "//WAP to write and read a structure using write() and read() function using a binary file.", "description": "#include 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<

24 =>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.

25 //WAP for reading and writing class object. #include class Student { char name[51]; char grade; float marks; public: void getdata(void); Void display(void); }; Void Student:: getdata(void) Char ch;

26 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< { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/14/4377295/slides/slide_26.jpg", "name": "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<

27 Detecting EOF: this function detect the end of the file is reached. Prototype int 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.

28 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); #2 seekp() –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( )

29 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

30 //WAP to searching in a file that has records maintained through structure. #include 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< { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/14/4377295/slides/slide_30.jpg", "name": "//WAP to searching in a file that has records maintained through structure.", "description": "#include 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<

31 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.

32 #include Class stu{ int rollno; char name[25],class[4],grade; float marks; public: void getdata( ) { cout >rollno; cout >name; Cout >class; Cout >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< { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/14/4377295/slides/slide_32.jpg", "name": "#include Class stu{ int rollno; char name[25],class[4],grade; float marks; public: void getdata( ) { cout >rollno; cout >name; Cout >class; Cout >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<rollno; cout >name; Cout >class; Cout >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<

33 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( ); }

34 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”);

35 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”);

36 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” ;

37 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 }

38 ERROR Handling during file I/O: Name Meaning eofbit -> 1 when end of file is encountered, 0 otherwise eailbit -> 1 when a non-fatal I/O error has occurred, 0 otherwise badbit -> 1 when a fatal I/O error has occurred, 0 otherwise goodbit -> 0 value

39 Function Meaning int 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.

40


Download ppt "VINAY ALEXANDER PGT(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."

Similar presentations


Ads by Google