SlideShare a Scribd company logo
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.
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");
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;
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;
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;
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()
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;
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);
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);
// 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.
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
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
{
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;
}
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();
}
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)
{
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;
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();
}
}

More Related Content

PPT
File handling in C++
PDF
file handling c++
PPTX
Polymorphism in C++
PPTX
Basic Concepts of OOPs (Object Oriented Programming in Java)
PPTX
Encapsulation
PPSX
Files in c++
PPTX
classes and objects in C++
File handling in C++
file handling c++
Polymorphism in C++
Basic Concepts of OOPs (Object Oriented Programming in Java)
Encapsulation
Files in c++
classes and objects in C++

What's hot (20)

PPT
File handling in_c
PDF
Python file handling
PDF
C++ Files and Streams
PPTX
Array of objects.pptx
PPTX
Inheritance In C++ (Object Oriented Programming)
PPTX
File in C language
PPTX
Namespace in C++ Programming Language
PPTX
Request dispacther interface ppt
PPTX
Array within a class
PPTX
Abstract class in c++
PPTX
PPTX
Sql fundamentals
PPT
08 c++ Operator Overloading.ppt
PPTX
Union in c language
PPTX
Data file handling in python introduction,opening & closing files
PPTX
C Programming: Structure and Union
PPTX
Applet and graphics programming
PPT
Introduction to Procedural Programming in C++
File handling in_c
Python file handling
C++ Files and Streams
Array of objects.pptx
Inheritance In C++ (Object Oriented Programming)
File in C language
Namespace in C++ Programming Language
Request dispacther interface ppt
Array within a class
Abstract class in c++
Sql fundamentals
08 c++ Operator Overloading.ppt
Union in c language
Data file handling in python introduction,opening & closing files
C Programming: Structure and Union
Applet and graphics programming
Introduction to Procedural Programming in C++
Ad

Viewers also liked (9)

PPT
File organization and indexing
PPT
Filehandlinging cp2
PPTX
Chapter 4 record storage and primary file organization
PPTX
basics of file handling
PPT
File handling
PPS
The Living World
PPT
Sql Server Basics
PPSX
Diversity in living organisms....
PPTX
MS Sql Server: Introduction To Database Concepts
File organization and indexing
Filehandlinging cp2
Chapter 4 record storage and primary file organization
basics of file handling
File handling
The Living World
Sql Server Basics
Diversity in living organisms....
MS Sql Server: Introduction To Database Concepts
Ad

Similar to File handling in c++ (20)

PPT
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
PPTX
Basics of file handling
PDF
Files and streams
PPTX
Stream classes in C++
PPT
File in cpp 2016
PPT
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
PPT
file_handling_in_c.ppt......................................
PDF
Chapter28 data-file-handling
PPTX
Data file handling in c++
PDF
Filesinc 130512002619-phpapp01
PPTX
13 file handling in C++.pptx oops object oriented programming
DOCX
Filehandling
PPTX
Chapter4.pptx
PPTX
File management in C++
PPTX
File Handling
PDF
Filepointers1 1215104829397318-9
PDF
streams and files
PPTX
Object Oriented Programming Using C++: Ch12 Streams and Files.pptx
PPTX
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
Basics of file handling
Files and streams
Stream classes in C++
File in cpp 2016
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
file_handling_in_c.ppt......................................
Chapter28 data-file-handling
Data file handling in c++
Filesinc 130512002619-phpapp01
13 file handling in C++.pptx oops object oriented programming
Filehandling
Chapter4.pptx
File management in C++
File Handling
Filepointers1 1215104829397318-9
streams and files
Object Oriented Programming Using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx

Recently uploaded (20)

PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Modernizing your data center with Dell and AMD
PPTX
Big Data Technologies - Introduction.pptx
PDF
Approach and Philosophy of On baking technology
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPT
Teaching material agriculture food technology
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Empathic Computing: Creating Shared Understanding
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Advanced IT Governance
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Advanced Soft Computing BINUS July 2025.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Modernizing your data center with Dell and AMD
Big Data Technologies - Introduction.pptx
Approach and Philosophy of On baking technology
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Teaching material agriculture food technology
Diabetes mellitus diagnosis method based random forest with bat algorithm
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Empathic Computing: Creating Shared Understanding
GamePlan Trading System Review: Professional Trader's Honest Take
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Advanced IT Governance
Chapter 3 Spatial Domain Image Processing.pdf
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Review of recent advances in non-invasive hemoglobin estimation
Advanced Soft Computing BINUS July 2025.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Dropbox Q2 2025 Financial Results & Investor Presentation

File handling in c++

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