Vous êtes sur la page 1sur 26

C++ Notes Data File Handling Class XII

Stream Class

Stream Class Type of Link Example

ifstream File – to – Memory ifstream fin;

ofstream Memory – to – File ofstream fout;

fstream File – to – Memory / Memory – to - File fstream finout;

Opening Mode

Constant Meaning Stream type

Input mode (Read mode) – File exist then open otherwise ifstream
ios::in
opening fail. fstream
Output mode (Write mode) – File exist then open and
ofstream
ios::out previous content discard (delete). File does not exist then
fstream
create new file.
Append mode (Write Mode) – File exist then open and
ofstream
ios::app previous content can not delete & file pointer move at end
fstream
for writing (Append). File does not exist then create new file.
Append mode (Read / Write mode) – File exist then open
ifstream
and previous content can not delete & file pointer at end.
ios::ate ofstream
File pointer capable for move any where for reading and
fstream
writing

Additional Mode

Binary mode – File read or writes in binary mode. File by


ifstream
default mode is text mode and it is consider ending of line
ios::binary ofstream
(“\n”) character but binary mode does not consider the “\n”
fstream
character.
It is used with output mode. File exists then open otherwise ofstream
ios::nocreate
opening fail. fstream
It is used with output mode. File exists then opening fail ofstream
ios::noreplace
otherwise create new file. fstream
It is used with output mode. File exists then open and ofstream
ios::trunc
previous content truncated (delete). Same as ios::out fstream

By Sunil Kumar Mobile No.: 9868583636 Page 1 of 26


C++ Notes Data File Handling Class XII

/* Text file handling program */


#include<fstream.h>
#include<stdio.h>
#include<ctype.h>
#include<conio.h>
#include<string.h>
#include<process.h>
void Create () // Function to create new text file
{
ofstream Fout;
char str[80], ch;
Fout.open(“Story.TXT”); // Open the file for write
do
{ cout<<”\n\t Enter Text “; gets (str);
Fout << str<<endl; // Write the string into the file
cout<<”\n Write more [Y/N] ? “; cin>>ch;
} while (toupper(ch) == ‘Y’ );
Fout.close (); // Close (disconnect) the link from data file
}
void AddAtEnd () // Function to add new line in existing file or create new file create
{
ofstream Fout;
char str[80], ch;
Fout.open(“Story.TXT”, ios:: app); // Open the file in append mode for add string
do
{
cout<<”\n\t Enter Text “; gets (str);
Fout<< str<<endl; // Write into File (Story.txt)
cout<<”\n Write more [Y/N] ? “; cin>>ch;
} while (toupper(ch) == ‘Y’ );
Fout.close ();
}
void Display()// Function to display the content of a text file
{
ifstream Fin;
char ch;
Fin.open(“Story.TXT”); // Open the file in read mode
if(!Fin) // Check for open the file successfully or Not
{ cout<<”Unable to open File “<<endl;
getch(); return;
}
while( !Fin.eof()) // Read a character & checks for end of file
{ fin>>ch;
cout<<ch;
}

By Sunil Kumar Mobile No.: 9868583636 Page 2 of 26


C++ Notes Data File Handling Class XII

Fin.close ();
}
1. Function count no. of line in a text file
void CountLine()
{
ifstream Fin;
char str[80];
Fin.open(“Story.TXT”, ios:: in);
int Cnt=0;
while(!Fin.eof()) // Read a line & Checks for end of file
{
Fin.getline(str, 80);
Cnt++;
}
Fin.close();
cout<<”\nNo. of Lines : “<<Cnt;
}
2. Function count no. of line start with –A- in a text file
int CountLineStartWithA()
{
ifstream Fin;
char str[80];
Fin.open(“Story.TXT”, ios:: in);
int Cnt=0;
while(!Fin.eof()) // Read a line & Checks for end of file
{
Fin.getline(str, 80)
if(toupper(str[0]) == ‘A’) // Check for First Letter is ‘A’ or Not
Cnt++;
}
Fin.close();
return Cnt; cout<<”No. of A:”<<Cnt; right or not // Return Counted no. of lines
}
3. Function count no. of word in a text file (File name input by user)
int CountWord()
{
ifstream Fin;
char str[80];
Fin.open(“Story.TXT”, ios:: in);
int Cnt=0;
while(!Fin.eof()) // Checks for end of file
{
Fin>>str; Fin.getline(str,80,’ ‘) // Read a word at a time
Cnt++;
}
Fin.close();
return Cnt;

By Sunil Kumar Mobile No.: 9868583636 Page 3 of 26


C++ Notes Data File Handling Class XII

}
4. Function count no. of word start with vowel & start with consonant in a text file
void CountVowelWord()
{
ifstream Fin;
char str[80];
Fin.open(“Story.TXT”, ios:: in);
int V=0,C=0;
while(!Fin.eof()) // Checks for end of file
{ Fin>>str; // Read a Word
if(isalpha(str[0])) // Check Alphabet or Not
{
switch(toupper(str[0])) // Pass the alphabet in uppercase for test
{
case ‘A’: case ‘E’: case ‘I’: case ‘O’: case ‘U’:
V++; break;
default:
C++; break;
}
}
}
Fin.close();
cout<<”\n\t No. of word start with Vowel: “<<V;
cout<<”\n\t No. of word start with Consonant: “<<C;
}

5. Function count no. of word ends with ed and ing


void CountWordEndwithEd()
{
ifstream Fin;
char str[80];
Fin.open(“Story.TXT”, ios:: in);
int i,ed=0, ing=0;

while(!Fin.eof()) // Checks for end of file


{ Fin>>str; // Read a Word
i = strlen(str) - 1;(may be for a word size) // Find the word last subscript
position
if(str[i-1] == ‘e’ && str[i] == ‘d’)
ed++;
else if(str[i-2] == ‘i’ && str[i-1] == ‘n’ && str[i] == ‘g’)
ing++;
}
Fin.close();
cout<<”\n\t No. of Word ending with – ed -: “<<ed;
cout<<”\n\t No. of Word ending with – ing -: “<<ing;
}

By Sunil Kumar Mobile No.: 9868583636 Page 4 of 26


C++ Notes Data File Handling Class XII

6. Function count separate – is - word in a text file


int CountWord_Is()
{
ifstream Fin;
char str[80];
Fin.open(“Story.TXT”, ios:: in);
int Cnt=0;
while(!Fin.eof()) // Checks for end of file
{ F>>str; // Read a word

if(strcmp(str,”is”) == 0) // Compare the string (word) is “is” or Not


Cnt++;
}
Fin.close();
return Cnt;
}

7. Function count No. of Alphabet, No. of Digits and No. of Blank Space in a text file
void CountNoofAlphabet()
{ ifstream Fin;
char ch;
Fin.open(“Story.TXT”, ios:: in);
int A=0, D=0, B=0;
while(!Fin.eof()) // Checks for end of file
{ Fin>>ch;
if(isalph(ch))
{
A++;
}
else if(isdigit(ch))
{
D++;
}
else if(ch == ‘ ‘)
{
B++;
}
}
Fin.close();
cout<<”\n\t No. of Alphabets : “<<A;
cout<<”\n\t No. of Digits : “<<D;
cout<<”\n\t No. of Blank Space : “<<B;
}
8. Function count No. of Vowels, No. of Consonants in a text file (same as Q.4)
void CountNoofVowel()
{

By Sunil Kumar Mobile No.: 9868583636 Page 5 of 26


C++ Notes Data File Handling Class XII

ifstream Fin;
char ch;
Fin.open(“Story.TXT”, ios:: in);
int V=0, C=0, B=0;
while(!Fin.eof()) // Read a Character & Checks for end of file
{ f>>ch;
if(isalph(ch))
{
switch(tolower(ch))
{
case ‘a’ :
case ‘e’ :
case ‘i’ :
case ‘o’ :
case ‘u’ :
V++;
break;
default :
C++;
}
}
else if(ch == ‘ ‘)
{
B++;
}
}
Fin.close();
cout<<”\n\t No. of Vowels : “<<V;
cout<<”\n\t No. of Consonants : “<<C;
cout<<”\n\t No. of Blank Space : “<<B;
}

9. Function a text file line by line and display reverse of line


void ReverseLine()
{
ifstream Fin;
char str[80];
Fin.open(“Story.TXT”, ios:: in);
int Cnt=0,i;
while(!Fin.eof()) // Read a line & Checks for end of file
{
Fin.getline(str, 80);
for(i = strlen(str) – 1; I >= 0; i--)
cout<<str[i];
cout<<endl;
}

By Sunil Kumar Mobile No.: 9868583636 Page 6 of 26


C++ Notes Data File Handling Class XII

Fin.close();
}

10. Function transfer the content of a text file into another text file.
void Transfer()
{
char Fname1[20], fname2[20];
fstream F1, F2;
cout<<”\n\t Enter Read File Name : “;
gets (Fname1); // Input 1st File name for read (Source File)
cout<<”\n\t Enter Write File Name : “;
gets (Fname2); // Input 2nd File name for write(Destination File)
F1.open (Fname1, ios::in);
F2.open (Fname2, ios::out);
char str[80];
if (!F1)
{
cout<<”\n\t Unable to open file “;
getch();
break;
}
while (!F1.eof()) // Read from file line by line & check end of file
{
F1.getline(str, 80)
F2<<str<<endl; // write line by line
}
F1.close();
F2.close();
}
void main()
{
int choice, N;
do
{
clrscr();
cout<<”\n\t Data File Menu (Text File) “;
cout<<”\n\t 1. Create “;
cout<<”\n\t 2. Add at End “;
cout<<”\n\t 3. Display “;
cout<<”\n\t 4. Count No. of Lines “;
cout<<”\n\t 5. Count No. of Lines start with -A- “;
cout<<”\n\t 6. Count No. of Word “;
cout<<”\n\t 7. Count No. of Vowel word and No. of Consonant Word”
cout<<”\n\t 8. Count No. of Word End with – ed- and – ing- “;
cout<<”\n\t 9. Count No. of Separate word – is- “;
cout<<”\n\t 10. Count No. of Alphabets, Digits, Blank Space “;
cout<<”\n\t 11. Count No. of Vowels and No. of Consonants”;

By Sunil Kumar Mobile No.: 9868583636 Page 7 of 26


C++ Notes Data File Handling Class XII

cout<<”\n\t 12. Display each line in reverse “;


cout<<”\n\t 13. Transfer one file into another file “;
cout<<”\n\t 14. Exit”;
cout<<”\n\t Enter choice [1-14] : “;
cin>>choice;
switch(choice)
{
case 1 :
Create();
break;
case 2 :
AddAtEnd();
break;
case 3 :
Display();
break;
case 4 :
CountLine();
break;
case 5:
N = CountLineStartWithA();
cout<<”\n\t No. of Line start with – A- : “<<N;
break;

case 6:
N = CountWord();
cout<<”\n\t No. of Word : “<<N;
break;
case 7:
CountVowelWord();
break;
case 8:
CountWordEndwithEd();
break;
case 9:
N = CountWord_Is();
cout<<”\n\t No. of separate Word – is - : “<<N;
break;
case 10:
CountNoofAlphabet();
break;
case 11:
CountNoofVowel();
break;
case 12:
ReverseLine();
break;

By Sunil Kumar Mobile No.: 9868583636 Page 8 of 26


C++ Notes Data File Handling Class XII

case 13:
Transfer();
break;
case 14:
cout<<”\n\t Quitting …… “;
break;
default:
cout<<”\n\t Invalid Choice … !!! “;
}
getch();
}
while (choice != 14);
}

Binary Files
Opening a binary file in OUTPUT mode (for writing on file)
At the time of opening the file in output mode the earlier content (if existing) gets deleted.

Syntax:
fstream <FileObject> ;
<FileObject>.open(<File Name>, ios::binary | ios ::out);

Example:
fstream F;
F.open(“STUDENT.DAT”, ios::binary | ios ::out);

By Sunil Kumar Mobile No.: 9868583636 Page 9 of 26


C++ Notes Data File Handling Class XII

Opening a binary file in INPUT mode (For reading from File)

Syntax:
fstream <FileObject> ;
<FileObject>.open(<File Name>, ios::binary | ios ::in);

Example:
fstream F;
F.open(“STUDENT.DAT”, ios::binary | ios ::in);

Opening a binary file in APPEND mode (For writing on file)


At the time of opening the file in append mode the earlier content (if existing) is not over
written and file write pointer moves to the end of file for adding new record at the bottom
of file.

Syntax:
fstream <FileObject> ;
<FileObject>.open(<File Name>, ios::binary | ios ::app);

Example:
fstream F;
F.open(“STUDENT.DAT”, ios::binary | ios ::app);

By Sunil Kumar Mobile No.: 9868583636 Page 10 of 26


C++ Notes Data File Handling Class XII

Binary files can be created in C++ with the help of variables of struct type data or objects of
class.
Using Structure Using Class
class Stock
struct Stock {
{ int ItemNo;
int ItemNo; char Item[20];
char Item[20]; float Price;
float Price; public:
}; void Input()
{ cin>>ItemNo; gets(Item); cin>>Price; }
void Output()
{ cout<<ItemNo<<’:’<<Item<<’:’<<Price;}
float getPrice() { return Price; }
int getItemNo() { return ItemNo; }
};

Creation of binary file with a record


void Create() void Create()
{ {
fstream F; fstream F;
Stock s1; Stock s1;
F.open(“Stock.dat”, ios::binary | ios::out); F.open(“Stock.dat”, ios::binary | ios::out);
// Read the information from user // Read the information from user
cout<<”\nItem No.: “; cin>>s1.ItemNo; s1.Input();
cout<<”\nItem : “; gets(s1.Item);
cout<<”\nPrice : “; cin>>s1.Price; // Write the information into the file
// Write the information into the fil F.write((char*) &s1, sizeof(s1));
F.write((char*) &s1, sizeof(s1)); F.close();
F.close(); }
}

Creation of binary file with multiple records


void Create() void Create()
{ {
char Choice; char Choice;
fstream F; fstream F;
Stock s1; Stock s1;
F.open(“Stock.dat”, ios::binary | ios::out); F.open(“Stock.dat”, ios::binary | ios::out);
do do
{ {
cout<<”\nItem No.: “; cin>>s1.ItemNo; S1.Input();
cout<<”\nItem : “; gets(s1.Item);
cout<<”\nPrice : “; cin>>s1.Price; // Write the record in file
F.write(open)((char*) &s1, sizeof(s1));

By Sunil Kumar Mobile No.: 9868583636 Page 11 of 26


C++ Notes Data File Handling Class XII

// Write the record in file cout<<”\nWrite More (Y/N) ? “;


F.write((char*) &s1, sizeof(s1)); cin>>Choice;(not decl. above)
cout<<”\nWrite More (Y/N) ? “; } while (Choice == ‘Y’ || Choice == ‘y’);
cin>>Choice; F.close();
} while (Choice == ‘Y’ || Choice == ‘y’); }
F.close();
}

Displaying a record from a binary file


void Display() void Display()
{ {
fstream F; fstream F;
Stock s1; Stock s1;
F.open(“Stock.dat”, ios::binary | ios::in); F.open(“Stock.dat”, ios::binary | ios::in);

// Checks for file open or not // Checks for file open or not
if( !F) if( !F)
{ {
cout<<”\n\t Unable to open file”; cout<<”\n\t Unable to open file”;
getch(); return; getch(); return; What is
} } difference
b/w upper
// Read a record from file // Read a record from file and lower
F.read((char*) &s1, sizeof(s1)); F.read((char*) &s1, sizeof(s1)); prog.
cout<<”\nItem No.: “<<s1.ItemNo; s1.Output();
cout<<”\nItem : “<<s1.Item; F.close();
cout<<”\nPrice : “<<s1.Price; }
F.close();
}
Displaying the entire content (all records) from a binary file
void Display() void Display()
{ {
fstream F; fstream F;
Stock s1; Stock s1;
F.open(“Stock.dat”, ios::binary | ios::in); F.open(“Stock.dat”, ios::binary | ios::in);
if( !F)
{ cout<<”\n\t Unable to open file”; if( !F)
getch(); return; {
} cout<<”\n\t Unable to open file”;
// Read a record & checks for end of file getch(); return;
while(F.read((char*) &s1, sizeof(s1))) }
{ // Read a record & checks for end of file
cout<<”\nItem No.: “<<s1.ItemNo; while(F.read((char*) &s1, sizeof(s1)))
cout<<”\nItem : “<<s1.Item; {
cout<<”\nPrice : “<<s1.Price; s1.Output();

By Sunil Kumar Mobile No.: 9868583636 Page 12 of 26


C++ Notes Data File Handling Class XII

} }
F.close(); F.close();
} }
Displaying the entire content (all records) from a binary file
which price below from given price (price in parameter)
void Display(float Pr) void Display( float Pr)
{ {
fstream F; fstream F;
Stock s1; Stock s1;
F.open(“Stock.dat”, ios::binary | ios::in); F.open(“Stock.dat”, ios::binary | ios::in);

if( !F) if( !F)


{ {
cout<<”\n\t Unable to open file”; cout<<”\n\t Unable to open file”;
getch(); return; getch(); return;
} }
// Read a record & checks for end of file // Read a record & checks for end of file
while(F.read((char*) &s1, sizeof(s1))) while(F.read((char*) &s1, sizeof(s1)))
{ {
// Check Price is below or not // Check Price is below or not
if(s1.Price < Pr) if(s1.getPrice() < Pr)
{ {
cout<<”\nItem No.: “<<s1.ItemNo; s1.Output();
cout<<”\nItem : “<<s1.Item; }
cout<<”\nPrice : “<<s1.Price; }
} F.close();
} }
F.close();
}
Searching for a record from a binary file
void Search(int N) void Search(int N)
{ {
fstream F; fstream F;
Stock s1; Stock s1;
int found=0; int found=0;
F.open(“Stock.dat”, ios::binary | ios::in); F.open(“Stock.dat”, ios::binary | ios::in);
if( !F) if( !F)
{ {
cout<<”\n\t Unable to open file”; cout<<”\n\t Unable to open file”;
getch(); return; getch(); return;
} }
// Read a record & checks for end of file // Read a record & checks for end of file
while(F.read((char*) &s1, sizeof(s1))) while(F.read((char*) &s1, sizeof(s1)))
{ {
// Check Item No. is equal to N or not // Check Item No. is equal to N or not

By Sunil Kumar Mobile No.: 9868583636 Page 13 of 26


C++ Notes Data File Handling Class XII

if(s1.ItemNo == N) if(s1.getItemNo() == N)
{ {
cout<<”\nItem No.: “<<s1.ItemNo; s1.Output();
cout<<”\nItem : “<<s1.Item; found++;
cout<<”\nPrice : “<<s1.Price; }
found++; }
} F.close();
} if(found == 0)
F.close(); cout<<”\n\t Record Not Found”;
if(found == 0)
cout<<”\n\t Record Not Found”; }
}

Count no. of record in a binary file


int CountRecord() int CountRecord()
{ {
fstream F; fstream F;
Stock s1; Stock s1;
int count=0; int count=0;
F.open(“Stock.dat”, ios::binary | ios::in); F.open(“Stock.dat”, ios::binary | ios::in);
if( !F) if( !F)
{ {
cout<<”\n\t Unable to open file”; cout<<”\n\t Unable to open file”;
getch(); return; getch(); return;
} }
// Read a record & checks for end of file // Read a record & checks for end of file
while(F.read((char*) &s1, sizeof(s1))) while(F.read((char*) &s1, sizeof(s1)))
{ {
count++; count++;
} }
F.close(); F.close();
return count; return count;
} }

Transferring the content of a binary file to another binary file.


void Transfer () void Transfer ()
{ {
fstream F1, F2; fstream F1, F2;
Stock s1; Stock s1;
F1.open(“Stock.dat”, ios::binary | ios::in); F1.open(“Stock.dat”, ios::binary | ios::in);
if( !F1)
if( !F1)
{
{
cout<<”\n\t Unable to open file”;
cout<<”\n\t Unable to open file”;
getch(); return;
getch(); return;
}
}

By Sunil Kumar Mobile No.: 9868583636 Page 14 of 26


C++ Notes Data File Handling Class XII

F2.open(“Stock2.dat”, ios::binary | ios::out); F2.open(“Stock2.dat”, ios::binary | ios::out);


// Read a record & checks for end of file // Read a record & checks for end of file
while(F1.read((char*) &s1, sizeof(s1))) while(F1.read((char*) &s1, sizeof(s1)))
{ {
F2.write((char*) &s1, sizeof(s1)); F2.write((char*) &s1, sizeof(s1));
} }
F1.close();
F1.close();
F2.close();
F2.close();
}
}

Insertion of a record in a Binary File (Sequential)


(Assuming file to be in ascending order of Item No.)
void Insertion () void Insertion ()
{ {
fstream F1, F2; fstream F1, F2;
Stock s1, Snew; Stock s1, Snew;
int Insert=0; int Insert=0;
F1.open(“Stock.dat”, ios::binary | ios::in); F1.open(“Stock.dat”, ios::binary | ios::in);
if( !F1) if( !F1)
{ {
cout<<”\n\t Unable to open file”; cout<<”\n\t Unable to open file”;
getch(); return; getch(); return;
} }
F2.open(“Temp.Dat”, ios::binary | ios::out); F2.open(“Temp.Dat”, ios::binary | ios::out);
// Read new Record to be Insert // Read new Record to be Insert
cout<<”\nItem No.: “; cin>>Snew.ItemNo; Snew.Input();
cout<<”\nItem : “; gets(Snew.Item); // Read a record & checks for end of file
cout<<”\nPrice : “; cin>>Snew.Price; while(F1.read((char*) &s1, sizeof(s1)))
{
// Read a record & checks for end of file if(Snew.getItemNo() < s1.getItemNo()
while(F1.read((char*) &s1, sizeof(s1))) && !Insert)
{ {
if(Snew.ItemNo < s1.ItemNo && !Insert) F2.write((char*) &Snew, sizeof(Snew));
{ Insert++;
F2.write((char*) &Snew, sizeof(Snew)); }
Insert++; F2.write((char*) &s1, sizeof(s1));
} }
F2.write((char*) &s1, sizeof(s1)); F1.close();
} F2.close();
F1.close(); remove(“Stock.dat”);
F2.close(); rename(“Temp.Dat”, “Stock.dat”);
remove(fname); }
rename(“Temp.Dat”, fname);
}

By Sunil Kumar Mobile No.: 9868583636 Page 15 of 26


C++ Notes Data File Handling Class XII

Delete a record from binary file


void Deletion () void Deletion ()
{ {
fstream F1, F2; fstream F1, F2;
Stock s1; Stock s1;
int Delete=0, Ino; int Delete=0,Ino;

F1.open(“Stock.dat”, ios::binary | ios::in); F1.open(“Stock.Dat”, ios::binary | ios::in);


if( !F1) if( !F1)
{ {
cout<<”\n\t Unable to open file”; cout<<”\n\t Unable to open file”;
getch(); return; getch(); return;
} }

F2.open(“Temp.Dat”, ios::binary | ios::out); F2.open(“Temp.Dat”, ios::binary | ios::out);

// User input Item No. to be deleted // User input Item No. to be deleted
cout<<”\n\tEnter Item No : “; cin>>Ino; cout<<”\n\tEnter Item No : “; cin>>Ino;

// Read a record & checks for end of file // Read a record & checks for end of file
while(F1.read((char*) &s1, sizeof(s1))) while(F1.read((char*) &s1, sizeof(s1)))
{ {
if(s1.ItemNo != Ino) if(s1.getItemNo() != Ino)
{ {
F2.write((char*) &Snew, sizeof(Snew)); F2.write((char*) &s1, sizeof(s1));
} }
else else
{ {
Delete++; Delete++;
} }
} }
F1.close(); F1.close();
F2.close(); F2.close();
remove(fname); remove(“Stock.Dat”);
rename(“Temp.Dat”, fname); rename(“Temp.Dat”, “Stock.Dat”);
if(Delete==0) if(Delete==0)
cout<<”\n\t Record Not found”; cout<<”\n\t Record Not found”;
else else
cout<<”\n\t Record deleted”; cout<<”\n\t Record deleted”;
} }

By Sunil Kumar Mobile No.: 9868583636 Page 16 of 26


C++ Notes Data File Handling Class XII

Adding a record at end of an existing binary file


void Create() void Create()
{ {
char fname[20]; char fname[20];
fstream F; fstream F;
Stock s1; Stock s1;
cout<<”\n\t File Name : “; gets(fname); cout<<”\n\t File Name : “; gets(fname);
F.open(fname, ios::binary | ios::app); F.open(fname, ios::binary | ios::app);
cout<<”\nItem No.: “; cin>>s1.ItemNo; s1.Input();
cout<<”\nItem : “; gets(s1.Item); F.write((char*) &s1, sizeof(s1));
cout<<”\nPrice : “; cin>>s1.Price; F.close();
F.write((char*) &s1, sizeof(s1)); }
F.close();
}

#include <fstream.h>
#include <conio.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
class EMP
{
int Eno;
char Name[20], Address[40];
public:
int GetEno() { return Eno; }
int Check ( char Names[]) { return strcmp(Name, Names); }
char *GetEname() { return Name; }
void In();
void EditAddress();
void Out();
};
Void EMP :: In()
{
cout<<”Eno :”; cin>>Eno;
cout<<”Name :”; gets(Name);
cout<<”Address : “; gets(Address);
}
void EMP :: EditAddress()
{
cout<<”Address : “; gets(Address);
}
void EMP :: Out()
{
cout<<”Eno :“<<Eno<<endl;

By Sunil Kumar Mobile No.: 9868583636 Page 17 of 26


C++ Notes Data File Handling Class XII

cout<<”Name :”<<Name<<” Address : “<<Address<<endl;


}

void Create() // To create a binary file with records of EMP class


{
char Choice;
fstream F;
EMP e1;
F.open(“EMP.DAT”, ios::binary | ios::out);
do
{
e1.In();
F.write((char*) &e1, sizeof(e1)); // Write the record in file
cout<<”\nWrite More (Y/N) ? “;
cin>>Choice;
} while (Choice == ‘Y’ || Choice == ‘y’);
F.close();
}

void AddatEnd() // To add new record in a binary file with records of EMP class
{
fstream F;
EMP e1;
F.open(“emp.dat”, ios::binary | ios::app);
e1.In();
F.write((char*) &e1, sizeof(e1));
F.close();
}

void Display() // To display the contents of binary file


{
fstream F;
EMP e1;
F.open(“EMP.DAT”, ios::binary | ios::in);
if( !F)
{
cout<<”\n\t Unable to open file”;
getch(); return;
}
// Read a record & checks for end of file
while(F.read((char*) &e1, sizeof(e1)))
{
e1.Out();
}
F.close();
}

By Sunil Kumar Mobile No.: 9868583636 Page 18 of 26


C++ Notes Data File Handling Class XII

void Search() // To search the record by EMP No


{
fstream F;
EMP e1;
int found=0, no;
cout<<”\n\tEnter Empno to be search: “; cin>>no;
F.open(“EMP.DAT”, ios::binary | ios::in);
if( !F)
{
cout<<”\n\t Unable to open file”;
getch(); return;
}
while(F.read((char*) &e1, sizeof(e1))) // Read a record & checks for end of file
{
if(e1.GetEno() == no) // Check Emp No. is equal to no or not
{
e1.Output();
found++;
}
}
F.close();
if(found == 0)
cout<<”\n\t Record Not Found”;
}

void SearchName() // To search the record by EMP No


{
fstream F;
EMP e1;
int found=0, status;
char n[20];
cout<<”\n\tEnter Name to be search: “; gets(n);
F.open(“EMP.DAT”, ios::binary | ios::in);
if( !F)
{
cout<<”\n\t Unable to open file”;
getch(); return;
}
while(F.read((char*) &e1, sizeof(e1))) // Read a record & checks for end of file
{
status = e1.Check(n); // Check Name is equal of no. Is equal then return “0”
if(status == 0)
{
e1.Output();
found++;
}
}

By Sunil Kumar Mobile No.: 9868583636 Page 19 of 26


C++ Notes Data File Handling Class XII

F.close();
if(found == 0)
cout<<”\n\t Record Not Found”;
}
To Sort a binary file in Ascending order of Eno ( Numeric Field)
void SortEno()
{
Fstream F;
F.open(“EMP.DAT”, ios::binary | ios::in | ios::out);
F.seekg(0, ios::end); // To Move the record pointer to end of file
int NOR = F.tellg() / sizeof(EMP); // To find number of records in the file
EMP e1, e2;
int i, j;
// Using Bubble Sort Method
for( i =0; i<NOR-1; i++)
{
for( j= 0; j< (NOR – i – 1); j++)
{
F.seekg( j * sizeof(EMP)); // To move the file pointer to jth position
F.read ((char*) &e1, sizeof(EMP)); // Read (j) the record
F.read ((char*) &e2, sizeof(EMP)); // Read (j+1) the record
if( e1.GetEno() > e2.GetEno())
{
F.seekp(j* sizeof(EMP));
F.write((char*) &e2, sizeof(EMP));
F.write((char*)&e1, sizeof(EMP));
}
}
}
F.close();
}

To Sort a binary file in Ascending order of Ename ( String)


void SortEname()
{
Fstream F;
F.open(“EMP.DAT”, ios::binary | ios::in | ios::out);
F.seekg(0, ios::end); // To Move the record pointer to end of file
int NOR = F.tellg() / sizeof(EMP); // To find number of records in the file
EMP e1, e2;
int i, j;
// Using Bubble Sort Method
for( i =0; i<NOR-1; i++)
{
for( j= 0; j< (NOR – i – 1); j++)

By Sunil Kumar Mobile No.: 9868583636 Page 20 of 26


C++ Notes Data File Handling Class XII

{
F.seekg( j * sizeof(EMP)); // To move the file pointer to jth position
F.read ((char*) &e1, sizeof(EMP)); // Read (j) th record
F.read ((char*) &e2, sizeof(EMP)); // Read (j+1) the record
if( strcmpi(e1.GetEname(), e2.GetEname()) > 0)
{
F.seekp(j* sizeof(EMP));
F.write((char*) &e2, sizeof(EMP));
F.write((char*)&e1, sizeof(EMP));
}
}
}
F.close();
}

To edit <Address> field of a particular Record in a binary file


void Modify()
{
Fstream F;
F.open(“EMP.DAT”, ios::binary | ios::in | ios::out);
EMP E;
int No, Pos, Found=0;
cout<<” Enter Emp no : “;
cin>>No;

while( !Found && F.read((char*) &E, sizeof(E)) )


{
if(E.GetEno() == No)
{
E.EditAddress();
Pos = F.tellg() – sizeof(E); // Find the search’s record position
F.seekp(Pos); // Moves file pointer for re-write edited record
F.write((char*) &E, sizeof(E));
Found++;
}
}
if( !Found)
cout<<”No record matching for editing …… “<<endl;
F.clsoe();
}

By Sunil Kumar Mobile No.: 9868583636 Page 21 of 26


C++ Notes Data File Handling Class XII

void main()
{
int Choice;
do
{
clrscr();
cout<<”\n\t Data File Menu (Binary File)”;
cout<<”\n\t1. Create “
cout<<”\n\t2. Display “
cout<<”\n\t3. Append “;
cout<<”\n\t4. Search Name “;
cout<<”\n\t5. Search Emp No. “;
cout<<”\n\t6. Sort Name Wise”;
cout<<”\n\t7. Sort Emp no wise “;
cout<<”\n\t8. Modify “;
cout<<”\n\t9. Quit”;
cout<<”\n\t Enter Choice [1-9] : “;
cin>>Choice;
switch(Choice)
{
case 1:
Create(); break;
case 2:
Display(); getch(); break;
case 3:
AddatEnd(); break;
case 4:
Search(); getch(); break;
case 5:
SearchName(); getch(); break;
case 6:
SortEno(); break;
case 7:
SortEname(); break;
case 8:
Modify(); getch(); break;
case 9:
cout<<”\n\t Quitting ……”; getch(); break;
default:
cout<<”\n\t Invalid Choice !!!!”; getch();
}
}
while( Choice != 9);
}

By Sunil Kumar Mobile No.: 9868583636 Page 22 of 26


C++ Notes Data File Handling Class XII

Functions/Keywords associated with File Handling in C++


 sizeof() - A keyword uses in C++ which return no. of bytes required by a particular
variable / object or a data type.
Example
int A; float B, double C, char D, char str[25];
cout<<sizeof(A); // will display 2
cout<<sizeof(B); // will display 4
cout<<sizeof(C); // will display 8
cout<<sizeof(D); // will display 1
cout<<sizeof(str); // will display 25

 open() - A member function of fstream, ifstream, ofstream used to open a file in a


particular stream.
Header File <fstream.h>
Syntax
<fstream object>.open ( <char*-Filename>, <int-Filemode>);
Example
fstream F;
F.open ( “STUDENT.DAT”, ios::binary | ios::in);

 close() - A member function of fstream, ifstream, ofstream used to close a file.


Header File <fstream.h>
Syntax
<fstream object>.close();
Example
fstream F;
F.open (“STUDENT.DAT”, ios::binary | ios::in);
:
F.close();

 read() - A member function of istream/ifstream/fstream, used to extract a no. of


characters.
Header File : <iostream.h> and <fstream.h>
Syntax :
<fstream object> . read(<char*>, <int>);
Example
fstream F; Student S;
F.open(“STUD.DAT”, ios::binary | ios::in);
F.read((char*) &S, sizeof(S));
S.Output();
F.close();
 write() - A member function of ostream/ofstream/fstream, used to insert a no. of
characters.
Header File : <iostream.h> and <fstream.h>
Syntax :
<fstream object> . write(<char*>, <int>);
Example

By Sunil Kumar Mobile No.: 9868583636 Page 23 of 26


C++ Notes Data File Handling Class XII

fstream F; Student S;
F.open(“STUD.DAT”, ios::binary | ios::out);
S.Input();
F.write((char*) &S, sizeof(S));
F.close();
 eof() - A member function of ios, returns a non-zero value at the end of file.
Header File : <iostream.h> and <fstream.h>
Syntax:
eof(<fstream object>)
Example
fstream F; Student S;
F.open(“STUD.DAT”, ios::binary | ios::in);
F.read((char*) &S, sizeof(S));
if( !F.eof())
S.Output();
F.close();

 get() - A member function of istream/ifstream/fstream, used to extract next


character/eof.
Header Files <iostream.h> and <fstream.h>
Syntax
ifstream/istream object> . get();
Example
ifstream F (“LETTER.TXT”); char ch;
ch = F.get();
while(!F.eof())
{
cout<<ch;
ch = F.get();
}
F.close();

 put - A member function of ostream/ofstream/fstream, used to insert a character.


Header Files <iostream.h> and <fstream.h>
Syntax
ofstream/ostream object> . get();
Example
ofstream F (“LETTER.TXT”); char ch;
do
{
ch=getche();
if(ch != 27)
F.put(ch);
}
while (ch != 27);
F.close();

By Sunil Kumar Mobile No.: 9868583636 Page 24 of 26


C++ Notes Data File Handling Class XII

 getline () - A member function ofistream, used to extract characters upto the size
given/upto the delimeter whichever encountered first.
Header File - <iostream.h> and <fstream.h>
Syntax
<istream/ifstream object> . getline ( <char*>, <int>) ;
<istream/ifstream object> . getline ( <char*>, <int>, <char>) ;
Example
ifstream F; char str[80];
F.open(“LETTER.TXT”);
F.getline(str,80);
while( ! F.eof())
{
cout<<str<<endl;
F.getline(str,80);
}
F.close();

 tellg() - A member function of ifstream, used to return the current byte position in a
binary file.
Header File <fstream.h>
Syntax
int <ifstream object > . tellg() ;
Example
fstream F;
F.open (“EMP.DAT” , ios::binary | ios::in);
EMP E;
F.read((char*) &E, sizeof(E)); // Reading First Record
F.read((char*) &E, sizeof(E)); // Reading Second Record
int N = F.tellg() / sizeof(EMP);
cout<<”\n\tRecord Number : “<<N; // Output is 2
F.close();

 tellp() - A member function of ofstream, used to return the current byte position in a
binary file.
Header File <fstream.h>
Syntax
int <ofstream object > . tellp() ;
Example
fstream F;
F.open (“EMP.DAT” , ios::binary | ios::in | ios::out );
EMP E1, E2 ;
E2.Input();
F.write((char*) &E1, sizeof(E1)); // Reading First Record
E2.Input();
F.write((char*) &E2, sizeof(E2)); // Writing Second Record
int N = F.tellp() / sizeof(EMP);
cout<<”\n\tRecord Number : “<<N; // Output is 2

By Sunil Kumar Mobile No.: 9868583636 Page 25 of 26


C++ Notes Data File Handling Class XII

F.close();
 seekg() - A member function of ifstream, used to move the file pointer to a specified
byte position in a binary file.
Header File <fstream.h>
Syntax
<ifstream object> . seekg(<Byte Position>) ;
<ifstream object> . seekg(<Byte Position>, <seek_dir>) ;
<seek_dir> : ios::beg, ios::cur, ios::end
Example
Fstream F;
F.open(“EMP.DAT”, ios::bina
ry | ios::in);
EMP E;
F.seekg(4* sizeof(EMP)); // Moves the file pointer to 5th record
F.read((char*) &E, sizeof(E)); // Reading 5th record
E.Display();
F.close();
 seekp() - A member function of ofstream, used to move the file pointer to a specified
byte position in a binary file.
Header File <fstream.h>
Syntax
<ofstream object> . seekp(<Byte Position>) ;
<ofstream object> . seekp(<Byte Position>, <seek_dir>) ;
<seek_dir> : ios::beg, ios::cur, ios::end
Example
Fstream F(“EMP.DAT”, ios::binary | ios::in);
EMP E; E.Input();
F.seekp(4* sizeof(EMP)); // Moves the file pointer to 5th record
F.write((char*) &E, sizeof(E)); // Writing 5th record
F.close();

Streams
A stream is used to manage flow of bytes. An input stream (istream) manages bytes flowing
into the program, and an output stream (ostream) manages bytes flowing out of the
program. Instance (object) of the class istream (cin) represents the standard input device
(i.e. keyboard). Instance (object) of the class ostream (cout) manages the output of data
from the program to the standard output device (i.e.screen / Monitor).
In C++, a data file is simply an external stream (a sequence of bytes stored on a disk). If a file
is opened for output (for writing on to the file), then it is an output file stream (ofstream). If
the file is opened for input (for reading from file), then it is an input file stream (ifstream).
#include<fstream.h>
istream ostream
Keyboard void main() Screen
{ char str[80];
cin int a; cin>>a; cout<<a; cout
fstream inFile,outFile;
inFile.open(“A1.TXT”, ios::in);
outFile.open(“A2.TXT”, ios::out);
Data File ifstream outFile<<”Hello”<<endl; ofstream Data File
inFile.getline(str,80); cout<<str<<endl;
inFile inFile.close(); outFile.close(); OutFile
}

By Sunil Kumar Mobile No.: 9868583636 Page 26 of 26