• Save
File handling in c++
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

File handling in c++

on

  • 1,460 views

 

Statistics

Views

Total Views
1,460
Views on SlideShare
1,460
Embed Views
0

Actions

Likes
4
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

File handling in c++ Document Transcript

  • 1. Introduction to streams C++ still supports the entire C I/O system. However, C++ supplies a complete set of object oriented I/O routines. To perform file I/O, you must include the header file fstream.h in your program. It contains declaration of several classes, including ifstream, ofstream and fstream. These classes are derived from istream and ostream. In C++, a file is opened by linking it to a stream. There are three types of streams: input, output, and input/output. To create an input stream, declare an object of type ifstream. To create an output stream, declare an object of type ofstream. To create an input/output stream, declare an object of type fstream. Once you have created a stream, one way to associate it with a file is by using the function open(). About function open() Prototype of function open is: open(const char *filename, openmode mode); Here filename is the name of file, which can include a path specifier. The value of mode determines how the file is opened. It must be a value of type openmode, which is an enumeration defined by ios that contains the following values: o ios::app o ios::ate o ios::binary o ios::in o ios::out o ios::trunc You can combine two or more of these values by ORing them together. Including ios::app causes all output to that file to be appended to the end. This value can be used only with files capable of output. Including ios::ate causes a seek to the end of the file to occur when the file is opened. Although I/O operations can still occur anywhere with in the file. The ios::in value specifies that the file is capable of input. The ios::out value specifies that the file is capable of output. The ios::binary value causes a file to be opened in binary mode. By default, all files are opened in text mode. The ios::trunc value causes the contents of a preexisting file by the same name to be destroyed and the file to be truncated to zero length 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.
  • 2. Example .1 #include<iostream> #include<fstream> #include<string> #include<conio.h> using namespace std; int main() { ofstream fout(“file.txt”); fout<<”This is first line.n”; fout<<”This is second line.n”; fout.close(); string x; ifstream fin(“file.txt”); while(!fin.eof()) { getline(fin,x); cout<<x<<endl; } getch(); } Output: This is first line. This is second line. Reading and writing To perform reading and writing you need to use member functions of one of the class from ifstream, ofstream or fstream. Commonly used member function to read file content is read() and member function to write file content is write() Example 2: #include<iostream> #include<conio.h> #include<fstream> using namespace std; int menu() { system("cls");
  • 3. cout<<"n1. Read File"; cout<<"n2. Write File"; cout<<"n3. Exit"; cout<<"nnEnter your choice"; int ch; cin>>ch; return(ch); } void reading() { ifstream fin("c:tc3file0.dat"); char x; if(!fin) cout<<"File not found"; else { while(fin>>x) cout<<x; } fin.close(); } void writing() { ofstream fout("c:tc3file0.dat"); char x; if(!fout) cout<<"File can not open"; else { cout<<"Press Enter to Submit String"<<endl; do { x=getche(); if(x==13) break; fout<<x; }while(1); } fout.close(); } int main() { int ch;
  • 4. while(1) { ch=menu(); switch(ch) { case 1: reading(); break; case 2: writing(); break; case 3: exit(0); default: cout<<"Enter Valid choice"; } getch(); } } Example 3: #include<iostream> #include<conio.h> #include<fstream> #include<iomanip> using namespace std; class Book { int bookid; char title[30]; float price; public: Book() { bookid=0; strcpy(title,""); price=0.0;} void getbook() { cout<<"Enter Book ID: "; cin>>bookid; cout<<"Enter Book Title: "; fflush(stdin); gets(title); cout<<"Price of Book: "; cin>>price; } void showheader() { cout<<left;
  • 5. cout<<"n"<<setw(10)<<"BOOK ID"<<setw(10)<<"Price"<<setw(10)<<"Titlen"; } void showbook() { cout<<left; cout<<"n"<<setw(10)<<bookid<<setw(10)<<price<<setw(10)<<title; } void reading(); void writing(); }; int menu() { system("cls"); cout<<"n1. Read File"; cout<<"n2. Write File"; cout<<"n3. Exit"; cout<<"nnEnter your choice"; int ch; cin>>ch; return(ch); } void Book:: reading() { ifstream fin; char x; fin.open("c:tc3file1.dat",ios::in|ios::binary); if(!fin) cout<<"File not found"; else { showheader(); fin.read((char*)this,sizeof(*this)); while(!fin.eof()) { fin.read((char*)this,sizeof(*this)); showbook(); } } fin.close(); } void Book::writing() { ofstream fout; char x;
  • 6. fout.open("c:tc3file1.dat",ios::out|ios::app|ios::binary); if(!fout) cout<<"File can not open"; else fout.write((char*)this,sizeof(*this)); fout.close(); } int main() { Book b; int ch; while(1) { ch=menu(); switch(ch) { case 1: b.reading(); break; case 2: b.getbook(); b.writing(); break; case 3: exit(0); default: cout<<"Enter Valid choice"; } getch(); } } List of Important functions to handle file open() This function is member of ifstream as well as ofstream class. This function is used to open file in a particular mode. File modes and functioning of open() function is already discussed in this chapter. Syntax File_object.open( file name, file mode); close()
  • 7. 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: Syntax file_object.close(); get() get() function is defined in class istream. There are several version of get() defined in istream class and derived in ifstream. 1) int get(); Example 4: #include<iostream> #include<conio.h> #include<fstream> using namespace std; int main() { ifstream fin; fin.open("example.txt",ios::in); while(!fin.eof()) cout<<fin.get(); fin.close(); getch(); } If file example.txt contains integer values get function read one integer at a time and returns the same. If file contains text, get function returns its corresponding ASCII code. Since in above program file example.txt has opened in text mode (as we do not mention binary mode) it is a good idea to replace statement cout<<fin.get(); by cout<<(char)fin.get();. It converts ASCII code into corresponding character. 2) istream& get(char&); Example 5: #include<iostream> #include<conio.h> #include<fstream> using namespace std; int main() { ifstream fin; char ch;
  • 8. fin.open("example.txt",ios::in); fin.get(ch); while(!fin.eof()) { cout<<ch; fin.get(ch); } fin.close(); getch(); } This time get function is used to take character from input stream and store in char variable. 3) istream& get(char *s, streamsize n, char delim); Example 6: #include<iostream> #include<conio.h> using namespace std; int main() { char str[10]; cin.get(str,10,'n'); cout<<str; getch(); } This function inputs characters till ‘n’ appears of 10 characters. getline() istream& getline (char* s, streamsize n, char delim ); Extracts characters from the input sequence and stores them as a c-string into the array beginning at s. Characters are extracted until either (n - 1) characters have been extracted or the delimiting character is found (which is delim if this parameter is specified, or 'n' otherwise). Example 7: #include <iostream> using namespace std; int main () { char name[256], title[256]; cout << "Enter your name: "; cin.getline (name,256);
  • 9. cout << "Enter your favourite movie: "; cin.getline (title,256); cout << name << "'s favourite movie is " << title; } read() istream& read ( char* s, streamsize n ); This function is used to read data from input stream. You can use it to read data input from keyboard or file. Example 8: Input data from keyboard #include<iostream> #include<conio.h> using namespace std; int main() { char str[10]; cin.read(str,5); cout<<str; getch(); } Here, read function is used to input 5 characters form keyboard and store them to char array str. Example 9: 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.seekg (0, ios::end); length = fin.tellg(); fin.seekg (0, ios::beg);
  • 10. // allocate memory: buffer = new char [length]; // read data as a block: fin.read (buffer,length); fin.close(); cout.write (buffer,length); delete[] buffer; return 0; } In the above program first we calculate length of the file. This is done by using function seekg() 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 by file pointer. Our next job is to allocate memory using keyword new equal to the size of file. Lastly, output data with cout. write() Syntax ostream& write ( const char* s , streamsize n ); Writes the block of data pointed by s, with a size of n characters, into the output buffer. The characters are written sequentially until n have been written. Please refer example 3 of this chapter, and see the code of writing function to understand use of write function. tellg() This function is defined in istream class Returns the absolute position of the get pointer. Get pointer is a pointer to file. The get pointer determines the next location in the input sequence to be read by the next input operation. Refer example 9 to understand the use of tellg() tellp() This function is defined in ostream class Returns the absolute position of the put pointer. put pointer is a pointer to file.
  • 11. The put pointer determines the location in the output sequence where the next output operation is going to take place. Example 10: #include <fstream> #include <conio.h> using namespace std; int main () { long int pos; ofstream fout; fout.open ("example.txt"); fout.write ("This is an apple",16); pos=fout.tellp(); fout.seekp (pos-7); fout.write (" sam",4); fout.close(); getch(); } seekg() syntax istream& seekg ( streampos pos ); Sets the position of the get pointer. The get pointer determines the next location to be read in the source associated to the stream. Refer example 9 to understand its implementation. Pos could be value returned by tellg() Another version of seekg() is istream& seekg ( streamoff off, ios_base::seekdir dir ); Integral value of type streamoff representing the offset to be applied relative to an absolute position specified in the dir parameter. Seeking direction. It is an object of type ios_base::seekdir that specifies an absolute position from where the offset parameter off is applied. It can take any of the following member constant values: ios_base::beg beginning of the stream buffer ios_base::curcurrent position in the stream buffer ios_base::end end of the stream buffer
  • 12. seekp() Just like seekg(), seekp() used to set position of put pointer Syntax ostream& seekp ( streampos pos ); ostream& seekp ( streamoff off, ios_base::seekdir dir ); Sets the position of the put pointer. The put pointer determines the location in the output sequence where the next output operation is going to take place. Rest is same like seekg() eof() It is defined in ios class It is end of file (eof) The function returns 1 if the eofbit stream's error flag has been set by a previous i/o operation. This flag is set by all standard input operations when the End Of File is reached in the sequence associated with the stream. Otherwise it returns 0. Refer example 4 and 5 to understand the use of eof(). Example Program in C++ Using file handling to perform following operations: 1) add new record 2) View all records 3) Delete particular record 4) Search record 5) Update record #include<iostream> #include<fstream> #include<conio.h> #include<iomanip> #include<stdio.h> #include<string.h> using namespace std; int menu(); class Book
  • 13. { private: int bookid; char title[20]; float price; protected: int allotbookid(); void showheader(); public: void getbook(); void showbook(); void addbook(); void viewbook(); void searchbook(); void deletebook(); void modifybook(); }; int Book::allotbookid() { ifstream fin; Book temp; int id=0; fin.open("bookfile.txt",ios::in|ios::binary); if(!fin) return(id+1); else { fin.read((char*)&temp,sizeof(temp)); while(!fin.eof()) { id=temp.bookid; fin.read((char*)&temp,sizeof(temp)); } id++; return(id); } } void Book::showheader() { cout<<left; cout<<"n"<<setw(10)<<"BOOK ID"<<setw(10)<<"Price"<<setw(10)<<"Titlen"; } void Book::getbook() { cout<<"Enter Book Title: "; fflush(stdin); gets(title); cout<<"Price of Book: "; cin>>price; bookid=allotbookid(); } void Book::showbook() { cout<<left; cout<<"n"<<setw(10)<<bookid<<setw(10)<<price<<setw(10)<<title;
  • 14. } void Book::addbook() { ofstream fout; fout.open("bookfile.txt",ios::out|ios::app|ios::binary); if(!fout) cout<<"File can not open"; else fout.write((char*)this,sizeof(*this)); fout.close(); } void Book::viewbook() { ifstream fin; fin.open("bookfile.txt",ios::in|ios::binary); if(!fin) cout<<"File not found"; else { showheader(); fin.read((char*)this,sizeof(*this)); while(!fin.eof()) { showbook(); fin.read((char*)this,sizeof(*this)); } } fin.close(); } void Book::searchbook() { ifstream fin; char str[20]; fin.open("bookfile.txt",ios::in|ios::binary); cout<<"Enter the name of book to search:"; fflush(stdin); gets(str); if(!fin) cout<<"File not found"; else { fin.read((char*)this,sizeof(*this)); while(!fin.eof()) { if(!strcmp(this->title,str)) { showheader(); showbook(); break; } fin.read((char*)this,sizeof(*this)); } if(fin.eof()) cout<<"nRecord not found"; } fin.close();
  • 15. } void Book:: modifybook() { int id,r=0; fstream file; file.open("bookfile.txt",ios::in|ios::out|ios::ate|ios::binary); cout<<"nEnter record number to modify (bookid): "; cin>>id; file.seekg(0); if(!file) cout<<"File not found"; else { file.read((char*)this,sizeof(*this)); while(!file.eof()) { r++; if(bookid==id) { showheader(); showbook(); cout<<"nRe-enter book details:n"; cout<<"Enter book title:"; fflush(stdin); gets(title); cout<<"Enter book price"; cin>>price; file.seekp((r-1)*sizeof(Book),ios::beg); file.write((char*)this,sizeof(*this)); break; } file.read((char*)this,sizeof(*this)); } if(file.eof()) cout<<"Record not found"; } file.close(); } void Book:: deletebook() { ifstream fin; ofstream fout; int id; char x; fin.open("bookfile.txt",ios::in|ios::binary); fout.open("tempfile.txt",ios::out|ios::app|ios::binary); cout<<"Enter bookid to delete record"; cin>>id; if(!fin) cout<<"File not found"; else { fin.read((char*)this,sizeof(*this)); while(!fin.eof()) { if(this->bookid==id)
  • 16. { cout<<"Record you want to delete is:nn"; showheader(); showbook(); cout<<"nAre you sure you want to delete this record(y/n): "; fflush(stdin); cin>>x; if(x=='n') fout.write((char*)this,sizeof(*this)); else cout<<"nRecord is deleted"; } else fout.write((char*)this,sizeof(*this)); fin.read((char*)this,sizeof(*this)); } fin.close(); fout.close(); system("erase bookfile.txt"); getch(); system("rename tempfile.txt bookfile.txt"); } } int menu() { system("cls"); cout<<"n1. Add new book"; cout<<"n2. View all books"; cout<<"n3. Search book"; cout<<"n4. modify book"; cout<<"n5. delete book"; cout<<"n6. Exit"; cout<<"nnEnter your choice"; int ch; cin>>ch; return(ch); } int main() { Book b; int ch; while(1) { ch=menu(); switch(ch) { case 1: b.getbook(); b.addbook(); break; case 2: b.viewbook(); break;
  • 17. case 3: b.searchbook(); break; case 4: b.modifybook(); break; case 5: b.deletebook(); break; case 6: exit(0); default: cout<<"Enter Valid choice"; } getch(); } }