Вы находитесь на странице: 1из 18

C++

Chapter 12: File handling

-----------------------------------------------------------------------Chapter Contents Introduction to streams About function open() and file open modes Reading and writing List of important function to handle file Useful example

-----------------------------------------------------------------------Introduction to streams C++ still supports the entire C I/ s!stem" #owe$er% C++ supplies a complete set of ob&ect oriented I/ routines" 'o perform file I/ % !ou must include the header file fstream"h in !our program" It contains declaration of se$eral classes% including ifstream% ofstream and fstream" 'hese classes are deri$ed from istream and ostream" In C++% a file is opened b! lin(ing it to a stream" 'here are three t!pes of streams) input% output% and input/output" 'o create an input stream% declare an ob&ect of t!pe ifstream" 'o create an output stream% declare an ob&ect of t!pe ofstream. 'o create an input/output stream% declare an ob&ect of t!pe fstream" nce !ou ha$e created a stream% one wa! to associate it with a file is b! using the function open()" About function open() *rotot!pe of function open is) open(const char *filename, openmode mode); #ere filename is the name of file% which can include a path specifier" 'he $alue of mode determines how the file is opened" It must be a $alue of t!pe openmode% which is an enumeration defined b! ios that contains the following $alues) o ios))app o ios))ate o ios))binar! o ios))in o ios))out o ios))trunc +ou can combine two or more of these $alues b! Ring them together"

Including ios::app causes all output to that file to be appended to the end" 'his $alue can be used onl! with files capable of output" Including ios::ate causes a see( to the end of the file to occur when the file is opened" Although I/ operations can still occur an!where with in the file" 'he ios::in $alue specifies that the file is capable of input" 'he ios::out $alue specifies that the file is capable of output" 'he ios::binar $alue causes a file to be opened in binar! mode" ,! default% all files are opened in text mode" 'he ios::trunc $alue causes the contents of a preexisting file b! the same name to be destro!ed and the file to be truncated to -ero length

!e"t files 'ext file streams are those where we do not include the ios::binary flag in their opening mode" 'hese files are designed to store text and thus all $alues that we input or output from/to them can suffer some formatting transformations% which do not necessaril! correspond to their literal binar! $alue" .xample /0"/ #include<iostream> #include<fstream> #include<string> #include<conio.h> using namespace std; int main() { ofstream fout(file.txt ); fout<< !his is first line."n ; fout<< !his is second line."n ; fout.close(); string x; ifstream fin(file.txt ); #hile($fin.eof()) { getline(fin%x); cout<<x<<endl; & getch(); & utput) 'his is first line" 'his is second line"

#eading and $riting 'o perform reading and writing !ou need to use member functions of one of the class from ifstream% ofstream or fstream" Commonl! used member function to read file content is read() and member function to write file content is write() .xample /0"0) #include<iostream> #include<conio.h> #include<fstream> using namespace std; int menu() { system('cls'); cout<<'"n(. )ead *ile'; cout<<'"n+. ,rite *ile'; cout<<'"n-. .xit'; cout<<'"n"n.nter your choice'; int ch; cin>>ch; return(ch); & /oid reading() { ifstream fin('c:""tc-""file0.dat'); char x; if($fin) cout<<'*ile not found'; else { #hile(fin>>x) cout<<x; & fin.close(); & /oid #riting() { ofstream fout('c:""tc-""file0.dat'); char x; if($fout)

cout<<'*ile can not open'; else { cout<<'1ress .nter to 2ubmit 2tring'<<endl; do { x3getche(); if(x33(-) brea4; fout<<x; &#hile((); & fout.close(); & int main() { int ch; #hile(() { ch3menu(); s#itch(ch) { case (: reading(); brea4; case +: #riting(); brea4; case -: exit(0); default: cout<<'.nter 5alid choice'; & getch(); & & .xample /0"1) #include<iostream> #include<conio.h> #include<fstream> #include<iomanip> using namespace std; class 6oo4 { int boo4id;

char title7-08; float price; public: 6oo4() { boo4id30; strcpy(title%''); price30.0;& /oid getboo4() { cout<<'.nter 6oo4 9:: '; cin>>boo4id; cout<<'.nter 6oo4 !itle: '; fflush(stdin); gets(title); cout<<'1rice of 6oo4: '; cin>>price; & /oid sho#header() { cout<<left; cout<<'"n'<<set#((0)<<'6;;< 9:'<<set#((0)<<'1rice'<<set#((0)<<'!itle"n'; & /oid sho#boo4() { cout<<left; cout<<'"n'<<set#((0)<<boo4id<<set#((0)<<price<<set#((0)<<ti tle; & /oid reading(); /oid #riting(); &; int menu() { system('cls'); cout<<'"n(. )ead *ile'; cout<<'"n+. ,rite *ile'; cout<<'"n-. .xit'; cout<<'"n"n.nter your choice'; int ch; cin>>ch; return(ch); & /oid 6oo4:: reading() { ifstream fin; char x; fin.open('c:""tc-""file(.dat'%ios::in=ios::binary);

if($fin) cout<<'*ile not found'; else { sho#header(); fin.read((char>)this%si?eof(>this)); #hile($fin.eof()) { fin.read((char>)this%si?eof(>this)); sho#boo4(); & & fin.close(); & /oid 6oo4::#riting() { ofstream fout; char x; fout.open('c:""tc-""file(.dat'%ios::out=ios::app= ios::binary); if($fout) cout<<'*ile can not open'; else fout.#rite((char>)this%si?eof(>this)); fout.close(); & int main() { 6oo4 b; int ch; #hile(() { ch3menu(); s#itch(ch) { case (: b.reading(); brea4; case +: b.getboo4(); b.#riting(); brea4; case -: exit(0); default:

cout<<'.nter 5alid choice'; & getch(); & & %ist of Important functions to handle file open() 'his function is member of ifstream as well as ofstream class" 'his function is used to open file in a particular mode" 2ile modes and functioning of open() function is alread! discussed in this chapter" 3!ntax 2ile4ob&ect"open( file name% file mode)5 close() 6hen we are finished with our input and output operations on a file we shall close it so that its resources become a$ailable again" In order to do that we ha$e to call the stream7s member function close()" 'his member function ta(es no parameters% and what it does is to flush the associated buffers and close the file) 3!ntax file4ob&ect"close()5 get() get() function is defined in class istream" 'here are se$eral $ersion of get() defined in istream class and deri$ed in ifstream" 1) int get(); &"ample 12.' #include<iostream> #include<conio.h> #include<fstream> using namespace std; int main() { ifstream fin; fin.open('example.txt'%ios::in); #hile($fin.eof()) cout<<fin.get(); fin.close(); getch(); &

If file example"txt contains integer $alues get function read one integer at a time and returns the same" If file contains text% get function returns its corresponding A3CII code" 3ince in abo$e program file example"txt has opened in text mode (as we do not mention binar! mode) it is a good idea to replace statement cout<<fin.get(); b! cout<<(char)fin.get();" It con$erts A3CII code into corresponding character" 2) istream& get(char&); &"ample 12.( #include<iostream> #include<conio.h> #include<fstream> using namespace std; int main() { ifstream fin; char ch; fin.open('example.txt'%ios::in); fin.get(ch); #hile($fin.eof()) { cout<<ch; fin.get(ch); & fin.close(); getch(); & 'his time get function is used to ta(e character from input stream and store in char $ariable" )) istream* get(char +s, streamsi-e n, char delim). &"ample 12./ #include<iostream> #include<conio.h> using namespace std; int main() { char str7(08; cin.get(str%(0%@"n@); cout<<str; getch(); & 'his function inputs characters till 89n: appears of /; characters"

getline() istreamA getline (char> s% streamsi?e n% char delim ); .xtracts characters from the input se<uence and stores them as a c=string into the arra! beginning at s" Characters are extracted until either (n - 1) characters ha$e been extracted or the delimiting character is found (which is delim if this parameter is specified% or @"n@ otherwise)" &"ample 12.0 #include <iostream> using namespace std; int main () { char name7+BC8% title7+BC8; cout << '.nter your name: '; cin.getline (name%+BC); cout << '.nter your fa/ourite mo/ie: '; cin.getline (title%+BC); cout << name << '@s fa/ourite mo/ie is ' << title;
&

read() istreamA read ( char> s% streamsi?e n ); 'his function is used to read data from input stream" +ou can use it to read data input from (e!board or file" &"ample 12.1: Input data from 2e board #include<iostream> #include<conio.h> using namespace std; int main() { char str7(08; cin.read(str%B); cout<<str; getch(); &

#ere% read function is used to input > characters form (e!board and store them to char arra! str" &"ample 12.3: Input data from file #include <iostream> #include <fstream> using namespace std; int main () { int length; char > buffer; ifstream fin; fin.open ('example.txt'% ios::binary ); // get length of file: fin.see4g (0% ios::end); length 3 fin.tellg(); fin.see4g (0% ios::beg); // allocate memory: buffer 3 new char 7length8; // read data as a block: fin.read (buffer%length); fin.close(); cout.#rite (buffer%length); delete78 buffer; return 0; & In the abo$e program first we calculate length of the file" 'his is done b! using function see(g() which is used to set file pointer (will be discussed in detail later in this chapter)" tellg() tells the length of file from beginning to current position in the file point to b! file pointer" ur next &ob is to allocate memor! using (e!word new e<ual to the si-e of file" Lastl!% output data with cout" $rite() 3!ntax ostream& write ( const char* s , streamsize n );

6rites the bloc( of data pointed b! s% with a si-e of n characters% into the output buffer" 'he characters are written se<uentiall! until n ha$e been written" *lease refer example /0"1 of this chapter% and see the code of writing function to understand use of write function" tellg() 'his function is defined in istream class Returns the absolute position of the get pointer" ?et pointer is a pointer to file" 'he get pointer determines the next location in the input se<uence to be read b! the next input operation" Refer example /0"@ to understand the use of tellg() tellp() 'his function is defined in ostream class Returns the absolute position of the put pointer" put pointer is a pointer to file" 'he put pointer determines the location in the output se<uence where the next output operation is going to ta(e place" &"ample 12.14 #include <fstream> #include <conio.h> using namespace std; int main () { long int pos; ofstream fout; fout.open ('example.txt'); fout.#rite ('!his is an apple'%(C); pos3fout.tellp(); fout.see4p (posDE); fout.#rite (' sam'%F); fout.close(); getch();
&

see2g()

s nta" istreamA see4g ( streampos pos ); 3ets the position of the get pointer" 'he get pointer determines the next location to be read in the source associated to the stream" Refer example /0"@ to understand its implementation" *os could be $alue returned b! tellg() Another $ersion of see(g() is istreamA see4g ( streamoff off% iosGbase::see4dir dir ); Integral $alue of t!pe streamoff representing the offset to be applied relati$e to an absolute position specified in the dir parameter" 3ee(ing direction" It is an ob&ect of t!pe ios4base))see(dir that specifies an absolute position from where the offset parameter off is applied" It can ta(e an! of the following member constant $alues) iosGbase::beg beginning of the stream buffer iosGbase::curcurrent position in the stream buffer iosGbase::end end of the stream buffer see2p() Aust li(e see(g()% see(p() used to set position of put pointer Syntax ostreamA see4p ( streampos pos ); ostreamA see4p ( streamoff off% iosGbase::see4dir dir ); 3ets the position of the put pointer" 'he put pointer determines the location in the output se<uence where the next output operation is going to ta(e place" Rest is same li(e see(g() eof() It is defined in ios class It is end of file (eof) 'he function returns ( if the eofbit stream7s error flag has been set b! a pre$ious i/o operation" 'his flag is set b! all standard input operations when the .nd f 2ile is reached in the se<uence associated with the stream" therwise it returns ;" Refer example /0"B and /0"> to understand the use of eof() &"ample 5rogram to perform follo$ing operations: 1) add ne$ record

2) )) ') ()

6ie$ all records 7elete particular record 8earch record 9pdate record

#include<iostream> #include<fstream> #include<conio.h> #include<iomanip> #include<stdio.h> #include<string.h> using namespace std; int menu(); class 6oo4 { pri/ate: int boo4id; char title7+08; float price; protected: int allotboo4id(); /oid sho#header(); public: /oid getboo4(); /oid sho#boo4(); /oid addboo4(); /oid /ie#boo4(); /oid searchboo4(); /oid deleteboo4(); /oid modifyboo4(); &; int 6oo4::allotboo4id() { ifstream fin; 6oo4 temp; int id30; fin.open('boo4file.txt'%ios::in=ios::binary); if($fin) return(idH(); else { fin.read((char>)Atemp%si?eof(temp)); #hile($fin.eof()) { id3temp.boo4id; fin.read((char>)Atemp%si?eof(temp)); &

idHH; return(id); & & /oid 6oo4::sho#header() { cout<<left; cout<<'"n'<<set#((0)<<'6;;< 9:'<<set#((0)<<'1rice'<<set#((0)<<'!itle"n'; & /oid 6oo4::getboo4() { cout<<'.nter 6oo4 !itle: '; fflush(stdin); gets(title); cout<<'1rice of 6oo4: '; cin>>price; boo4id3allotboo4id(); & /oid 6oo4::sho#boo4() { cout<<left; cout<<'"n'<<set#((0)<<boo4id<<set#((0)<<price<<set#((0)<<ti tle; & /oid 6oo4::addboo4() { ofstream fout; fout.open('boo4file.txt'%ios::out=ios::app= ios::binary); if($fout) cout<<'*ile can not open'; else fout.#rite((char>)this%si?eof(>this)); fout.close(); & /oid 6oo4::/ie#boo4() { ifstream fin; fin.open('boo4file.txt'%ios::in=ios::binary); if($fin) cout<<'*ile not found'; else {

sho#header(); fin.read((char>)this%si?eof(>this)); #hile($fin.eof()) { sho#boo4(); fin.read((char>)this%si?eof(>this)); & & fin.close(); & /oid 6oo4::searchboo4() { ifstream fin; char str7+08; fin.open('boo4file.txt'%ios::in=ios::binary); cout<<'.nter the name of boo4 to search:'; fflush(stdin); gets(str); if($fin) cout<<'*ile not found'; else { fin.read((char>)this%si?eof(>this)); #hile($fin.eof()) { if($strcmp(thisD>title%str)) { sho#header(); sho#boo4(); brea4; & fin.read((char>)this%si?eof(>this)); & if(fin.eof()) cout<<'"n)ecord not found'; & fin.close(); & /oid 6oo4:: modifyboo4() { int id%r30; fstream file; file.open('boo4file.txt'%ios::in=ios::out=ios::ate= ios::binary); cout<<'"n.nter record number to modify (boo4id): '; cin>>id;

file.see4g(0); if($file) cout<<'*ile not found'; else { file.read((char>)this%si?eof(>this)); #hile($file.eof()) { rHH; if(boo4id33id) { sho#header(); sho#boo4(); cout<<'"n)eDenter boo4 details:"n'; cout<<'.nter boo4 title:'; fflush(stdin); gets(title); cout<<'.nter boo4 price'; cin>>price; file.see4p((rD()>si?eof(6oo4)%ios::beg); file.#rite((char>)this%si?eof(>this)); brea4; & file.read((char>)this%si?eof(>this)); & if(file.eof()) cout<<')ecord not found'; & file.close(); & /oid 6oo4:: deleteboo4() { ifstream fin; ofstream fout; int id; char x; fin.open('boo4file.txt'%ios::in=ios::binary); fout.open('tempfile.txt'%ios::out=ios::app= ios::binary); cout<<'.nter boo4id to delete record'; cin>>id; if($fin) cout<<'*ile not found'; else { fin.read((char>)this%si?eof(>this));

#hile($fin.eof()) { if(thisD>boo4id33id) { cout<<')ecord you #ant to delete is:"n"n'; sho#header(); sho#boo4(); cout<<'"nIre you sure you #ant to delete this record(yJn): '; fflush(stdin); cin>>x; if(x33@n@) fout.#rite((char>)this%si?eof(>this)); else cout<<'"n)ecord is deleted'; & else fout.#rite((char>)this%si?eof(>this)); fin.read((char>)this%si?eof(>this)); & fin.close(); fout.close(); system('erase boo4file.txt'); getch(); system('rename tempfile.txt boo4file.txt'); & & int menu() { system('cls'); cout<<'"n(. Idd ne# boo4'; cout<<'"n+. 5ie# all boo4s'; cout<<'"n-. 2earch boo4'; cout<<'"nF. modify boo4'; cout<<'"nB. delete boo4'; cout<<'"nC. .xit'; cout<<'"n"n.nter your choice'; int ch; cin>>ch; return(ch); &

int main() { 6oo4 b; int ch; #hile(() { ch3menu(); s#itch(ch) { case (: b.getboo4(); b.addboo4(); brea4; case +: b./ie#boo4(); brea4; case -: b.searchboo4(); brea4; case F: b.modifyboo4(); brea4; case B: b.deleteboo4(); brea4; case C: exit(0); default: cout<<'.nter 5alid choice'; & getch(); & &

Вам также может понравиться