You are on page 1of 17

FILE Handling in C++ program Files are used to store data in a relatively permanent form, on floppy disk, hard

disk, tape or other form of secondary storage. Files can hold huge amounts of data if need be. Ordinary variables (even records and arrays) are kept in main memory which is temporary and rather limited in size. The following is a comparison of the two types of storage 1. Main Memory 2 Secondary Memory C++ provides the following classes to perform output and input of characters to/from files: ofstream: Stream class to write on files ifstream: Stream class to read from files fstream: Stream class to both read and write from/to files. Data Type ofstream ifstream fstream Description This data type represents the output file stream and is used to create files and to write information to files. This data type represents the input file stream and is used to read information from files. This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.

To perform file processing in C++, header files <fstream.h> must be included in your C++ source file. These classes are derived directly or indirectly from the classes istream, and ostream. We have already used objects whose types were these classes: cin is an object of class istream and cout is an object of class ostream. Therfore, we have already been using classes that are related to our file streams. And in fact, we can use our file streams the same way we are already used to use cin and cout, with the only difference that we have to associate these streams with physical files. Open a file The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file. An open file is represented within a program by a stream object (an instantiation of one of these classes, in the previous example this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it. There are two methods of opening a file Constructor Open Statement In order to open a file with a stream object we use its member function open(): open (filename, mode); Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags: ios::in Open for input operations or read mode ios::out Open for output operations or write mode ios::binary Open in binary mode. ios::ate Set the initial position at the end of the file.

If this flag is not set to any value, the initial position is the beginning of the file. ios::app All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations. ios::trunc If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one. ios::nocreate Open for output operation but will not create a file only replaces the previous contents of the file. ios::no replace Open for output operation but will not replace the previous contents only create a new file. All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open(): ofstream myfile; myfile.open ("example.bin", ios::out | ios::app | ios::binary); Each one of the open() member functions of the classes ofstream, ifstream and fstream has a default mode that is used if the file is opened without a second argument: Since the first task that is performed on a file stream object is generally to open a file, these three classes include a constructor that automatically calls the open() member function and has the exact same parameters as this member. Therefore, we could also have declared the previous myfile object and conducted the same opening operation in our previous example by writing: ofstream myfile ("example.bin", ios::out | ios::app | ios::binary); Combining object construction and stream opening in a single statement. Both forms to open a file are valid and equivalent. To check if a file stream was successful opening a file, you can do it by calling to member is_open() with no arguments. This member function returns a bool value of true in the case that indeed the stream object is associated with an open file, or false otherwise: if (myfile.is_open()) { /* ok, proceed with output */ } class default mode parameter ofstream ios::out ifstream ios::in fstream ios::in | ios::out For ifstream and ofstream classes, ios::in and ios::out are automatically and respectivelly assumed, even if a mode that does not include them is passed as second argument to the open() member function. The default value is only applied if the function is called without specifying any value for the mode parameter. If the function is called with any value in that parameter the default mode is overridden, not combined. File streams opened in binary mode perform input and output operations independently of any format considerations. Non-binary files are known as text files, and some translations may occur due to formatting of some special characters (like newline and carriage return characters). Closing a file 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: myfile.close(); Once this member function is called, the stream object can be used to open another file, and the file is available again to be opened by other processes. In case that an object is destructed while still associated with an open file, the destructor automatically calls the member function close(). Text files Text file streams are those where we do not include the ios::binary flag in their opening mode. These files are designed to store text and thus all values that we input or output from/to them can suffer some formatting transformations, which do not necessarily correspond to their literal binary value. Data output operations on text files are performed in the same way we operated with cout: // writing on a text file #include <iostream> #include <fstream> void main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; } [fileexample.txt]: This is a line. This is another line. Data input from a file can also be performed in the same way that we did with cin: // reading a text file #include <iostream> This is a line. #include <fstream> #include <string> void main () { char line[80]; ifstream myfile ("example.txt"); if (myfile.is_open()) { while (myfile.getline(line,80))) { cout << line << endl; } myfile.close(); } else cout << "Unable to open file"; }

Output: This is a line. This is another line. This last example reads a text file and prints out its content on the screen. Notice how we have used a new member function, called eof() that returns true in the case that the end of the file has been reached. We have created a while loop that finishes when indeed myfile.eof() becomes true (i.e., the end of the file has been reached). Checking state flags eof() Returns true if a file open for reading has reached the end. Text Files (Program #include <fstream.h> #include <conio.h> //Text File Handling Program #include <ctype.h> #include <stdio.h> void Create() //Function to create new Text File { char Ch; cout<<"Delete the existing data(if any),Are You Sure (Y/N)?";cin>>Ch; if (toupper(Ch)=='Y') { fstream Fil; char Lin[80],Q; Fil.open("STUD.TXT",ios::out); do { cout<<Enter Text; gets(Lin); Fil<<Lin<<endl; cout<<More(Y/N)?;cin>>Q; } while (Q==Y); Fil.close(); } } void AddAtEnd() //Function to Add new lines to an existing Text File { fstream Fil; char Lin[80],Q; Fil.open("STUD.TXT",ios::app); do { cout<<Enter Text;gets(Lin); Fil<<Lin<<endl; cout<<More(Y/N)?;cin>>Q; } while (Q==Y); Fil.close(); } void Display() //Function to Display the content

{ //of a Text File fstream Fil; char Lin[80]; Fil.open("STUD.TXT",ios::in); while (Fil.getline(Lin,80)) cout<<Lin<<endl; Fil.close(); }int Count() //Function to Count the number { //of lines in a Text File fstream Fil; Fil.open("STUD.TXT",ios::in); char Lin[80];int Cnt=0; while (Fil.getline(Lin,80)) Cnt++; Fil.close(); return Cnt; } void main() { clrscr(); char Choice; do { cout<<"The no.of Lines in file:"<<Count()<<" Objects ..."<<endl; cout<<"C:Create/A:Addatend/D:Display/Q:Quit"<<endl;cin>>Choice; switch(Choice) { case 'C':Create();break; case 'A':AddAtEnd();break; case 'D':Display();break; } } while (Choice!='Q'); }

#include<fstream.h> //** BINARY FILE HANDLING ** #include<stdio.h> #include<conio.h> struct stud { int rno; char name[10]; int marks; }; void create() // FUNCTION TO CREATE NEW FILE { stud rec; fstream fl; fl.open("test.dat", ios::out|ios::binary); for (int i = 1;i<=4;i++) {

cout <<"r.no. : "; cin>>rec.rno; cout <<"name : " ; gets(rec.name); cout <<"marks : " ; cin>>rec.marks; fl.write((char * )&rec,sizeof(rec)); } fl.close(); } void addatend() // FUNCTION TOADD NEW RECORDS { stud rec; // AT END OF THE FILE fstream fl; char Q; fl.open("test.dat", ios::app | ios::binary); do { cout <<"\nEnter The Record : \n\n"; cout <<"r.no. : "; cin>>rec.rno; cout <<"name : " ; gets(rec.name); cout <<"marks : " ; cin>>rec.marks; fl.write((char * )&rec,sizeof(rec)); cout <<"\nMore <Y/N>:";cin>>Q; } while(Q=='Y'); fl.close(); } void display() // FUNCTION TO DISPLAY ALL RECORDS { stud rec; fstream fl; fl.open("test.dat", ios::in); fl.read((char * )&rec,sizeof(rec)); while (fl) //or while (!fl.eof()) { cout <<"\nr.no. : "<<rec.rno; cout <<"\nname : " <<rec.name; cout <<"\nmarks : "<<rec.marks; fl.read((char * )&rec,sizeof(rec)); } fl.close(); getch(); } void search() // FUNCTION TO SEARCH RECORD { // FOR GIVEN ROLL NO. stud rec;

fstream fl; clrscr(); int r,found=0; cout <<"Give Roll No To Be Searched : "; cin >>r; fl.open("test.dat", ios::in); fl.read((char * )&rec,sizeof(rec)); while (fl)// while (!fl.eof()) { if (rec.rno==r) { cout <<"\nr.no. : "<<rec.rno; cout <<"\nname : " <<rec.name; cout <<"\nmarks : "<<rec.marks; found=1; } fl.read((char * )&rec,sizeof(rec)); } if (found==0) cout <<"\nInvalid Roll No."; fl.close(); getch(); } void main() { char choice; do{ clrscr(); cout<<"\n\n\tC:Create\n\tA:Add at end\n\tD:Display"; cout<<"\n\tS:Search\n\tQ:Quit\n\t";cin>>choice; switch(choice) { case 'C' : create();break; case 'A' : addatend();break; case 'D' : display();break; case 'S' : search();break; } } while(choice!='Q'); } #include<fstream.h> #include<conio.h> #include<stdio.h> #include<process.h> void count() { char fname[20],ch; cout<<"\n Enter the file name :"; gets(fname); ifstream fin(fname);

Count of characters and lines

char str[80]; int n=0,lines=0; while(fin.get(ch)) { n++; if(ch==\n) lines++; } cout<<"\n Total no. of characters:"; cout<<n; cout<<\n Total no of lines <<lines; fin.close(); } void count_line() { cout<<"\n Enter the file name :"; gets(fname); ifstream fin(fname); char str[80]; while(fin.getline(str,80)) line++; cout<<"\n No. of lines:"; cout<<line; fin.close(); } void count_alpha() { cout<<"\n Enter the file name :"; gets(fname); ifstream fin(fname); while(fin.get(ch)) { if(ch>=65&&ch<=90) upper++; else if(ch>='0'&&ch<='9') digit++; else if(ch==' ') word++; switch(ch) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o':

Another method of counting lines

Read Character by Character till eof

You can use isupper() etc functions but dont forget to include ctype.h

Another method is to read word by word using fin.getline(str,80, ) method

case 'O': case 'u': case 'U': vowel++; break; } } cout<<"\n Number of upper case characters :"; cout<<upper; cout<<"\n Number of vowels :"; cout<<vowel; cout<<"\n Number of digits :"; cout<<digit; cout<<"\n Number of words :"; cout<<word; fin.close(); } void modify_file() { char fname[80]; clrscr(); cout<<"\n\aENTER THE SOURCE FILE NAME"; gets(fname); fstream fin(fname,ios::in|ios::out); char ch1,ch2,ch; int choice; if(!fin) cout<<"\nFILE DOES'NT EXIST"; cout<<"\nENTER THE CHARACTER TO BE FOUND"; cin>>ch1; cout<<"\nENTER THE CHARARCTER TO REPLACE"; cin>>ch2; fin.seekp(0); while(fin.get(ch)) { if(ch==ch1) { fin.seekp(-1,ios::cur); fin<<ch2; } } fin.close(); getch(); } void copy_file() { char fname1[80],fname2[80];

clrscr(); cout<<"\n\aENTER THE SOURCE FILE NAME"; gets(fname); cout<<\n Enter Target file NAME; gets(fname2); fstream fin(fname,ios::in); Befor writing data can be converted like fstream fout(fname,ios::out); if (isupper(ch) char ch; ch=tolower(ch); if(!fin) cout<<"\nFILE DOES'NT EXIST"; while(fin.get(ch)) { After closing remove, fout<<ch; rename functions can be } used for deletion and fin.close(); modification fout.close(); getch(); }

File Position Pointers: Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg ("seek get") for istream and seekp ("seek put") for ostream. The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a stream or ios::end for positioning relative to the end of a stream. The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the file's starting location. Some examples of positioning the "get" file-position pointer are: // position to the nth byte of fileObject (assumes ios::beg) fileObject.seekg( n ); // position n bytes forward in fileObject fileObject.seekg( n, ios::cur ); // position n bytes back from end of fileObject fileObject.seekg( n, ios::end ); // position at end of fileObject fileObject.seekg( 0, ios::end ); ASSIGNMENT : Q Assuming the class VEHICLE given below, write function in C++ to perform following:

1. Write the objects of VEHICLE to a binary file. 2. Read the objects of VEHICLE from binary file and display them on screen. class VEHICLE { int wheels, passenger ; public : void inputdata( ) { cin >> wheels ; gets ( passenger) ; } void outputdata ( ) { cout<<wheels<< << passenger<<endl; } }; ********************************************************************** void create_file( ) { fstream fl; VEHICLE v; // ***** object of class VEHICAL created ********* Char ans; int size = sizeof(v);// _________________________//open the file in OUTPUT mode assuming file // name is VEHICAL.DAT use open( ) function do { v.inputdata( ); fl.write(________,_______);// WRITE THE CLASS OBJECT ON FILE cout <<\n Do you want to write another record in file :<y/n> : ; cin >> ans; } while (ans==Y || ans==y); _______________; // close the opened file } // end of create_file( ) function ****************************************************************** void display_file( ) { fstream fl; VEHICLE v; _________________________; //open the file in INPUT mode assuming file // name is VEHICAL.DAT using CONSTRUCTOR while( ___________ ) //check end of file { _________________________;// READ THE CLASS OBJECT FROM FILE v.outputdata( ); } _______________; // close the opened file } Q. Assuming the class DRINK, write functions in C++ to perform the following: 1. Write the object of DRINK on to a binary file. 2. Read objects of DRINK from the binary file and display on the screen class DRINK { int quantity; char name[10]; public: void getdata(){ gets(name); cin>>quantity;} void showdata(){cout<<quantity<< <<name<<endl;} };

Class: XII A, XII D The contents of a file can be deleted by opening a temporary file. Logic 1. Open the file in read mode 2. Open the temp file in write mode 3. Accept character to delete 4. Read file 5. If character is not matching write in temp file 6. Repeat step 4-5 till end of file 7. Close both the files 8. Remove original file 9. Rename the temp file. Program of updating text file #include<fstream.h> #include<stdio.h> #include<conio.h> void main() { fstream fin(abc.txt,ios::in); fstream fout(temp.txt,ios::out); char ch,ch1; cout<<\n enter character for deletion; cin>>ch1; while(fin.get(ch)) { If (ch!=ch1) fout<<ch; } fin.close(); fout.close(); remove(abc.txt); rename(temp.txt,abc.txt); } The contents of a file can be modified by two methods 1 Using temporary file 2 Without using temporary file

Write the non matching character in temp file. Remove the original file

Save temp file as original file retaining other data after removing the data to be deleted.

Logic of modification using temporary file 1. Open the file in read mode 2. Open the temp file in write mode 3. Accept character to find and replace 4. Read file 5. If character is not matching write in temp file and write replace character if matching 6. Repeat step 4-5 till end of file 7. Close both the files 8. Remove original file 9. Rename the temp file.

Program of updating text file #include<fstream.h> #include<stdio.h> #include<conio.h> void main() { fstream fin(abc.txt,ios::in); fstream fout(temp.txt,ios::out); char ch,ch1,ch2; cout<<\n enter character to find; cin>>ch1; cout<<\n Enter character to replace; cin>>ch2; while(fin.get(ch)) { If (ch!=ch1) fout<<ch; else fout<<ch2; } fin.close(); fout.close(); remove(abc.txt); rename(temp.txt,abc.txt); }

Write the original character of non matching character and replace character for matching in temp file. Remove the original file

Save temp file as original file retaining data after modification.

Once a character is read/write the file pointer moves to the next byte so inorder to rewrite seekp and seekg commands are used to move the file pointer. Seekp is put pointer for writing and seekg is a get pointer for reading. Fin.seekp(3); Place the file pointer on 3rd byte Fin.seekg(-2,ios::cur); Place file pointer 2 bytes back from current position More examples will be taken to explain the concept. Logic of modification withour using temp file. 1. Open the file in rewrite mode 2. Accept character to find and replace 3. Read file 4. If character is matching move file pointer back by 1 byte and write in file 5. Repeat step 3-4 till end of file 6. Close the files Program of updating text file #include<fstream.h> #include<stdio.h> #include<conio.h> void main() { fstream fin(abc.txt,ios::in|ios::out); char ch,ch1,ch2;

If character is matching move file pointer back by 1 byte and rewrite in the file.

cout<<\n enter character to find; cin>>ch1; cout<<\n enter character to replace; cin>>ch2; while(fin.get(ch)) { If (ch==ch1) { Fin.seekp(-1,ios::cur); fin<<ch2; } } fin.close(); } Sequential file organization : In sequential files updation is not possible in a single file, so two or more files are required for the same. Binary Data File is a file in which we read or write a whole record. We first need to design the layout or structure to write and then write in file. struct student { int roll; char name[20]; int marks; }; void write_file( ) { fstream outfl; outfl.open(stud.dat , ios :: out | ios::binary);// open file in binary and output mode student s; char rep; do { cout<<Enter data; cin >> s.roll; gets(s.name); cin >> s.marks; outfl.write((char*)&s , sizeof(s)); cout<<\n Want to add more; cin>>rep; }while(rep==y); outfl.close(); } void read_file( ) { fstream infl; infl.open(stud.dat , ios :: int | ios::binary);// open file in binary and input mode student s; while(infl.read((char *)&s,sizeof(s))) { cout<<Data:<<s.roll<<<\t<<s.name<<s.marks<<endl;

} infl.close(); } #include<fstream.h> //** BINARY FILE HANDLING ** #include<stdio.h> #include<conio.h> class stud { int rno; char name[10]; int marks; public: void getdata() { cout <<"rollno. : "; cin>>rno; cout <<"name : " ; gets(name); cout <<"marks : " ; cin>>marks; } void dispdata() { cout <<"\nr.no. : "<< rno; cout <<"\nname : " <<name; cout <<"\nmarks : "<<marks } int return_rno(){return rno;} }; void create() // FUNCTION TO CREATE NEW FILE { stud rec; fstream fl; fl.open("test.dat", ios::out|ios::binary); for (int i = 1;i<=4;i++) { rec.getdata(); fl.write((char * )&rec,sizeof(rec)); } fl.close(); } void addatend() // FUNCTION TOADD NEW RECORDS { stud rec; // AT END OF THE FILE fstream fl; char Q; fl.open("test.dat", ios::app | ios::binary); do { rec.getdata()

Class for writing in the file.

Open file to for writing Write the record in the file.

Open file for adding the data.

fl.write((char * )&rec,sizeof(rec)); cout <<"\nMore <Y/N>:";cin>>Q; } while(Q=='Y'); fl.close(); } void display() // FUNCTION TO DISPLAY ALL RECORDS { stud rec; fstream fl; fl.open("test.dat", ios::in); fl.read((char * )&rec,sizeof(rec)); while (fl) //or while (!fl.eof()) { rec.dispdata(); fl.read((char * )&rec,sizeof(rec)); } fl.close(); getch(); } void search() // FUNCTION TO SEARCH RECORD { // FOR GIVEN ROLL NO. stud rec; fstream fl; clrscr(); int r,found=0; cout <<"Give Roll No To Be Searched : "; cin >>r; fl.open("test.dat", ios::in); while(fl.read((char * )&rec,sizeof(rec))) { if (rec.return_rno==r) { rec.dispdata(); found=1; } } if (found==0) cout <<"\nInvalid Roll No."; fl.close(); getch(); } void Delete_rec() { stud s; int flag=0; ifstream ifile(fname,ios::binary); if(ifile==NULL) { cout<<"\n File does not exist"; return;

Read file to read a records from the file.

Search the rollno to display

} int r; cout<<\n Enter rollno for deltion; cin>>r; ofstream ofile("temp.dat",ios::binary); while(ifile.read((char*)&s,sizeof(STUD))) { if(r!=s.return_rno()) ofile.write((char*)&s,sizeof(STUD)); else flag=1; } if(flag==0)cout<<"\nRoll no does not exist"; else cout<<"\n Record deleted"; ifile.close(); ofile.close(); remove(fname); rename("temp.dat",fname); } void modify_rec() { STUD s; int flag=0; ifstream ifile(fname,ios::binary); int r; cout<<\n Enter rollno for modification; cin>>r; if(ifile==NULL) { cout<<"\n File does not exist"; return; } ofstream ofile("temp.dat",ios::binary); while(ifile.read((char*)&s,sizeof(STUD))) { if(r==s.return_rno()) { s.getdata(); flag=1; } ofile.write((char*)&s,sizeof(STUD)); } if(flag==0) cout<<"\nRoll no does not exist"; else cout<<"\n Record modified; ifile.close(); ofile.close(); remove(fname); rename("temp.dat",fname); }

void modify_rec() //using seekp { STUD s; int flag=0; fstream file(fname,ios::binary,ios::in| ios::binary); int r; cout<<\n Enter rollno for modification; cin>>r; if(file==NULL) { cout<<"\n File does not exist"; return; } while(file.read((char*)&s,sizeof(s))) { if(r==s.return_rno()) { s.getdata(); flag=1; file.seekp(} 1*sizeof(s),ios::cur); file.write((char*)&s,sizeof(STUD)); } if(flag==0)cout<<"\nRoll no does not exist"; else cout<<"\n Record modified; file.close(); }

You might also like