File Handling A file is a bunch of bytes stored on a storage device like a tape or a magnetic disk. In C++ file input / output facilities are implemented through a component header file of C++ standard library called fstream.h. A file at its lowest level is interpreted as a sequence of bytes. The fstream.h header file has 3 classes that help to perform file input and output. Ifstream class for input (to read a file) Ifstream (the input stream ) reads the data from the file and supplies it to the program. Ofstream class for output ( to write on a file) Ofstream receives data from the program and writes the received data to the file. Fstream for both input and output (to both read and write on to a file) C++ contains a set of classes that define the file handling functions. These classes are declared within fstream.h. So we have to include this header file when working with files. Fstream is derived from iostream the header file which manages console I/O operations. Fstream.h header file contains the classes ifstream, fstream.,ofstream which are derived from fstreambase class and provides operations common to both input and output. It also contains open( ) and close( ) functions. Ifstream inherits get(), getline( ), read( ) , seekg( ) and tellg( ) , close(), open( ) Ofstream inherits put( ), write( ), seekp( ), tellp( ), open( ), close( ) Fstream inherits all the functions. Data files A text file stores information in ACII characters. In text files each line of text is terminated with a special character known as EOL. In text files some internal translations take place when this EOL character is read or written. A binary file is file which stores information in the same format as it is stored in the memory. There is no delimiter. Also no translations take place. Binary files are faster and easier to read. Opening and closing files Opening of files can be achieved in two ways Using constructor function of the stream class Using open() ifstream f1; f1.open(“file.txt”);
ifstream f1(“File.txt”);
Filemode describes how a file is to used. ifstream 1) ios::in file is opened for writing ofstream 1) ios::out file is opened for writing. If the file does not exist, it is created. 2) ios::ate opens the file at end. Can write anywhere in the file. 3) ios::app causes the output to be appended to the end of the file. 4) ios::trunc causes the contents of the file to be destroyed and truncates the file to zero length. If the file does exist it gives an error. 5) ios::nocreate File should exist from before for open( ) to work, otherwise it will give an error message.
6) ios::noreplace File should not exist from before for open( ) to work., otherwise open( ) fails. Used when you want to create new file 7) ios::binary Causes file to be opened in binary mode. To close a file f1.close( ) Get( ) is used to read single characters from the user while getline( ) is used to read strings. Put( ) is used to write one character onto the file. Get() and put( ) are byte oriented. Getline(varname, size, delimiter). e.g. char line[20]; getline (line, 20, ‘;’); By default the delimiter is “\n”. The getline function reads characters form input stream and puts them into the buffer until either size number of characters have been read or the delimiter is encountered.
1)Create 2 text files #include #include void main( ) { clrscr( ); char ch; fstream f1, f2; f1.open(“First .txt”,ios::out); f1<<”My school is Carmel Convent\n”; f1<<”It is in Delhi”; f1.close(); f1.open(“First.txt”,ios::in); f2.open(“Second.txt”,ios::out); while(f1.get(ch)) { cout< #include ofstream fout; fout.open(“Marks.dat”); char ans = ‘Y’; int rollno; float marks; clrscr(); while( ans==’y’ || ans= = ‘Y’) { cout<<”Enter roll :” ; cin>>rollno; cout<<”Enter name”; gets(name); cout<<”Marks”; cin>>marks; fout<>ans; } fout.close( ); } To read the contents of file STORY.TXT and display the no of alphabets , vowels, no of words and no of empty spaces #include #include #include Ifstream f1; F1.open(“Story.txt”, ios::noreplace); char ch; int calpha= cvow= cspace=0; If(!fin) { cout<< “File does not exist” return; } While (fin.get(ch)
{ ch = toupper(ch) if (isalpha) { calpha++; if ( ch == ‘A’ || ch==”E’ || ch == ‘I’ || ch ==’O’ || ch ==’U’) cvow++; } if (ch == ‘ ‘) cspace ++; } cout<<”No of alpabets” < void main( ) { ofstream fn; fn.open(“Story.txt”,ios::out); fn << “Hello little boy \n”; fn<<”These are your books”; fn.close ( ); ifstream fillin; int countb = 0; fillin.open(“Story.txt); char line[80]; if(!fin) { cout<< “Error in opening file”; return -1; } while(fillin.getline(line,80, ‘\n’) cout<< line<<’\n’; fillin.seekg(0,ios::beg); while(fillin.getline(line, 80,’ ‘) if (line[0]== ‘B’) countb++; cout<<”no of words beginning with b are”< #include #include void main() { clrscr(); fstream f1; f1.open("olddata.txt",ios::in|ios::out); fstream nf; nf.open("newdata.txt",ios::out); char ch; f1<<"INteRneT RETRETE"; f1.seekg(0); cout<<endl<<"the 'oldData.txt file contains"<<endl; while(f1) {f1.get(ch); cout<64 && ch<91) ch=tolower(ch); else if(ch>96&&ch<123) ch=toupper(ch); nf.put(ch); } nf.close(); nf.open("newdata.txt",ios::in);
cout<<endl<<"the 'newData.txt'file contents are"<<endl; nf.seekg(0); while(nf) { nf.get(ch); cout< #include #include #include<string.h> #include<stdio.h> #include<process.h> class emp { int eno; char name[15]; float sal; public: void getdata(); void display(); void search(int); }e1; void emp::getdata() { ofstream f; f.open("empf.dat",ios::app||ios::binary); cout<<"Enter the eno"; cin>>eno; cout<<"enter the name"; gets(name); cout<<"Enter the salary"; cin>>sal; f.write((char*)this,sizeof(emp)); f.close(); } void emp::display() { fstream fin; fin.open("empf.dat",ios::in||ios::binary); fin.seekg(0); while(fin) { fin.read((char*)this,sizeof(emp)); cout<<"\nEno"<<'\t'<<eno; cout<<"\nEmployee name"; cout<<"\nEmployee sal"<<sal; } fin.close(); } void emp::search(int rno) { fstream fin; int loc; fin.open("empf.dat",ios::in||ios::binary); loc=rno-1*sizeof(emp); fin.seekg(loc); fin.read((char*)this,sizeof(emp)); cout<<"\nENO "<<eno; cout<<"\nEmployee name :"<
puts(name);
void main() { clrscr(); int c,rno; do { cout<<"\n\n1. Enter the data" <<"\n\n2. Display data" <<"\n\n3. Search" <<"\n\n4 Exit" <<"\n\n Enter your choice"; cin>> c; switch(c) { case 1 : e1.getdata(); break; case 2 : fstream fin; display(); break; case 3 : cout<<"Enter the record no to be searched "; cin>>rno; e1.search(rno); break; case 4 : cout<<"Bye! See you"; getch(); exit(0); default : cout<<"Enter the corrct choice"; } } while(c!=4); getch(); }
File Pointers and Random Access Every file has 2 pointers 1) get( ) and 2) Put( ) which tell the current position in the file where writing or reading will take place. These pointers help in random access in files. Seekg( ) and tellg( ) functions allow you to examine the get( ) pointer. (fstream) Seekp( ) and tellp( ) perform these operations on the put pointer. (ofstream) Fin.seekg( 0 ) beginning of the file Fin.seekg( 30, ios:: beg) – byte no 30 from beginning of the file. Fin.seekg(20, ios:: end) Fin.seekg( 2, ios:: curr) Tellg( ) and tellp( ) return the position of the put and get pointer.
Read a text file and display the no of bytes in it. Fstream fi; F1.seekg(0, ios::end) ; Int no_of_bytes = fin.tellp(); cout<<no_of_bytes; Q1. void main () { char ch = ‘A’; fstream fileout(“data.dat”, ios::out); fileout<>lino; while (fil.read((char *) &obj, sizeof(item))) { rec++; if(ino == lino) cout<< “Enter new details”; { obj.getdata( ); file.seekp((rec-1) * sizeof(student), ios::beg) file.write(char*) &obj; sizeof (item)); flag = -1; break; } if(flag == 0) cout<<”Record does not exist” else cout<<”\n Modified”; fil.close( ); } Q Following is a structure of each record in a data file named “Colony.dat” Struct Colony { char colony_code [10]; char colony_name[10]; int no_of_people; }; Write a function in C++ to update the file with a new value of no_of people. The value of colony_code and No_of_people are read during the execution of the program.