Académique Documents
Professionnel Documents
Culture Documents
Stream Class
Opening Mode
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
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;
}
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;
}
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()
{
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;
}
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”;
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;
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);
Syntax:
fstream <FileObject> ;
<FileObject>.open(<File Name>, ios::binary | ios ::in);
Example:
fstream F;
F.open(“STUDENT.DAT”, ios::binary | ios ::in);
Syntax:
fstream <FileObject> ;
<FileObject>.open(<File Name>, ios::binary | ios ::app);
Example:
fstream F;
F.open(“STUDENT.DAT”, ios::binary | ios ::app);
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; }
};
// 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();
} }
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(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”; }
}
// 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”;
} }
#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;
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();
}
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();
}
{
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();
}
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);
}
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();
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
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
}