DATA FILE HANDLING IN C++
Key Points:
• Text file: A text file stores information in readable and printable form. Each line of text is
terminated with an EOL (End of Line) character.
• Binary file: A binary file contains information in the non-readable form i.e. in the same format in
which it is held in memory.
• Stream: A stream is a general term used to name flow of data. Different streams are used to
represent different kinds of data flow.
• There are three file I/O classes used for file read / write operations.
o ifstream - can be used for read operations.
o ofstream - can be used for write operations.
o fstream - can be used for both read & write operations.
• fstream.h:
• This header file includes the definitions for the stream classes ifstream, ofstream and fstream.
In C++ file input output facilities implemented through fstream.h header file.
• It contain predefines set of operation for handling file related input and output, fstream class
ties a file to the program for input and output operation.
• A file can be opened using:
o By the constructor of the stream. This method is preferred when single file is used with
the stream.
o By the open() function of the stream.
• File modes:
• ios::out It creates file in output mode and allows writing into the file.
• ios::in It creates file in input mode and permit reading from the file.
• ios::app To retain the previous contents of the file and to append to the
end of existing file.
• ios::ate To place the file pointer at the end of the file, but you can write
data any where in the file.
• ios::trunc It truncates the existing file (empties the file).
• ios::nocreate If file does not exist this file mode ensures that no file is
created and open() fails.
• ios::noreplace If file does not exist, a new file gets created but if the file
already exists, the open() fails.
• ios::binary – Opens a file in binary mode.
eof(): This function determines the end-of-file by returning true(non-zero) for end of file otherwise
returning false(zero).
open():If you want to manage multiple file with same stream use open().
Stream_object.open(“Filename”,(Filemode));
e.g., fstream fio;
fio.open(“book.dat”, ios::in | ios::out | ios::binary);
The operator | is known as bitwise-OR operator.
close(): This function terminates the connection between the file and stream associated with it.
Stream_object.close();
read(): The read() function reads a fixed number of bytes from the specified stream and puts them in
the buffer.
Stream_object.read((char *)& Object, sizeof(Object));
write(): The write() function writes fixed number of bytes from a specific memory location to the
specified stream.
Stream_object.write((char *)& Object, sizeof(Object));
Note:
Both functions take two arguments.
• The first is the address of variable, and the second is the length of that variable in bytes. The
address of variable must be type cast to type char*(pointer to character type)
• The data written to a file using write( ) can only be read accurately using read( ).
25
file pointer: the file pointer indicates the position in the file at which the next input/output is to
occur.
seekg(): It places the file pointer to the specified position in a stream before input operation.
seekp(): It places the file pointer to the specified position in a stream before output operation.
tellg(): This function returns the current position of the file pointer in a stream.
tellp(): This function returns the current position of the file pointer in a stream.
Steps To Process A File
• Declare an opbject of the desired file stream class(ifstream, ofstream, or fstream)
• Open the required file to be processed using constructor or open function.
• Process the file.
• Close the file stream using the object of file stream.
e.g Open file book.txt,
ifstream fin(“book.txt”); read file and
char ch; display the character
fin>>ch; //fin.get(ch); from the file.
cout<<ch;
e.g,:
ofstream fout(“book.txt”); Create and open file
char ch; book.txt, write data
cin>>ch; into file from the
fout<<ch; // fout.put(ch); variable.
Exercise: 1 Mark Questions
1. Observe the program segment carefully and answer the question that follows:
class item
{int item_no;
char item_name[20];
public:
void enterDetail( );
void showDetail( );
int getItem_no( ){ return item_no;}
};
void modify(item x, int y )
{fstream File;
File.open( “item.dat”, ios::binary | ios::in | ios::out) ;
item i;
int recordsRead = 0, found = 0;
while(!found && File.read((char*) &i , sizeof (i)))
{recordsRead++;
if(i. getItem_no( ) == y )
{_________________________//Missing statement
File.write((char*) &x , sizeof (x)); found = 1;
}
}
if(! found)
cout<<”Record for modification does not exist” ;
File.close() ;
}
If the function modify( ) is supposed to modify a record in the file “ item.dat “, which item_no is
y, with the values of item x passed as argument, write the appropriate statement for the
missing statement using seekp( ) or seekg( ), whichever is needed, in the above code that
would write the modified record at its proper place.
If the function modify( ) modifies a record in the file “ item.dat “ with the values of item x
passed as argument, write the appropriate parameter for the missing parameter in the above
code, so as to modify record at its proper place.
26
Ans.1. File.seekp((recordsRead-1)*sizeof(x),ios::beg); or File.seekp(-1*sizeof(x),ios::cur);
General program structure used for operating a Text File
2 Marks Questions
Text files in input mode:
Write a function in a C++ to count the number of lowercase alphabets present in a text file
“BOOK.txt”.
int countalpha()
{ ifstream Fin(“BOOK.txt”);
char ch;
int count=0;
while(!Fin.eof())
{Fin.get(ch);
if (islower(ch))
count++;
}
Fin.close();
return count;
}
Function to calculate the average word size of a text file.
void calculate()
{ fstream File;
File.open(“book.txt”,ios::in);
char a[20];
char ch;
int i=0,sum=0,n=0;
while(File)
{ File.get(ch);
a[i]=ch;
i++;
if((ch==’ ‘) || ch(== ‘.’)||(char==’,’)(ch==’\t’)||(ch==’\n’)
{i --; sum=sum +i;
i=0; N++;
}
}
cout<<”average word size is “<<(sum/n);
}
Assume a text file “coordinate.txt” is already created. Using this file create a C++ function to
count the number of words having first character capital.
int countword()
{ ifstream Fin(“BOOK.txt”);
char ch[25];
int count=0;
while(!Fin.eof())
{Fin>>ch;
if (isupper(ch[0]))
count++;
}
Fin.close();
return count;
}
27
Function to count number of lines from a text files (a line can have maximum 70 characters or
ends at ‘.’)
int countword()
{ ifstream Fin(“BOOK.txt”);
char ch[70];
int count=0;
if (!Fin)
{ cout<<”Error opening file!” ;
exit(0);
}
while(1)
{Fin.getline(ch,70,‘.’);
if (Fin.eof())
break;
count++;
}
Fin.close();
return count;
}
A program to display the size of a file in bytes.
#include<iostream.h>
#include<fstream.h>
#include<process.h>
#include<conio.h>
int main()
{
char filename[13];
clrscr();
cout<”Enter Filename:\n”;
cin.getline(filename,13);
ifstream infile(filename);
if(!infile)
{cout>>”sorry ! Can not open “<<filename <<”file\n”;
exit(-1);
}
long no_bytes=0;
char ch;
infile.seekg(0,ios::end);
no_bytes=infile.tellg();
cout<<”File Size is”<<no_bytes<<”bytes\n”;
return 0;
}
Text files in output mode:
C++ program, which initializes a string variable to the content “There is an island of opportunity in the
middle of every difficulty.” and output the string one character at a time to the disk file “OUT.TXT”.
#include<fstream.h>
int main()
{ ofstream fout(“OUT.TXT”);
char *str = ”There is an island of opportunity in the middle of every difficulty.” ;
int i=0;
if(!fout)
{
cout<<”File cannot be opened “;
return 0;
}
while (str[i]!=’\0’)
28
{fout<<str[i];
i++;
}
fout.close();
}
Exercise: (2 Marks Questions)
1. te a function in a C++ to count the number of uppercase alphabets present in a text file
“BOOK.txt”
2. Write a function in a C++ to count the number of alphabets present in a text file “BOOK.txt”
3. Write a function in a C++ to count the number of digits present in a text file “BOOK.txt”
4. Write a function in a C++ to count the number of white spaces present in a text file “BOOK.txt”
5. Write a function in a C++ to count the number of vowels present in a text file “BOOK.txt”
6. Write a function in a C++ to count the average word size in a text file “BOOK.txt”
7. Write a function in C++ to print the count of the word “the” as an independent word in a text file
STORY.TXT.
For example, if the content of the file STORY.TXT is
There was a monkey in the zoo.
The monkey was very naughty.
Then the output of the program should be 2.
8. Assume a text file “Test.txt” is already created. Using this file, write a function to create three
files “LOWER.TXT” which contains all the lowercase vowels and “UPPER.TXT” which contains
all the uppercase vowels and “DIGIT.TXT” which contains all digits.
9. Create a function FileLowerShow() in c++ which take file name(text files)as a argument and
display its all data into lower case
10. Write a function in C++ to count the number of lines present in a text file “Story.txt”.
HOTS FILE HANDLING
1. Write a function in a C++ to count the number of consonants present in a text file “Try.txt”
2. Write a function in a C++ to count the number of uppercase vowels present in a text file
“Novel.txt”
3. Write a function in a C++ to display the sum of digits present in a text file “Fees.txt”.
4. Write a function in a C++ to display the product of digits present in a text file “Number.txt”.
5. Write a function in a C++ to find the largest digit present in a text file “Marks.txt”
3 Marks Questions
General program structure used for operating a Binary File
Program to read and write a structure using read() and write() using binary file.
struct student
{
char name[15];
float percent;
};
void main()
{
clrscr();
student s;
strcpy(s.name,”rasha”);
s.percent=89.50;
ofstream fout;
fout.open(“saving”, ios::out | ios:: binary);
if(!fout)
{
cout<<“File can’t be opened”;
29
break;
}
fout.write((char *) &s, sizeof(student));
fout.close();
ifstream fin;
fin.open(“saving”,ios::in | ios:: binary);
fin.read((char *) & s,sizeof(student));
cout<<s.name;
cout<<“\n has the percent: ”<<s.percent;
fin.close();
}
Function to add more objects belonging to class JOKE at the end of JOKES.DAT file.
class JOKE{int jokeid; char type[5], jokedesc[200];
public:
void Newjokeentry(){cin>>jokeid>>type; cin.getline(jokedesc,200);}
void showjoke(){cout<<jokeid<<”\t”<<type<<endl<<jokedesc<<endl;}
};
void append()
{
fstream afile;
afile.open(“JOKES.DAT”, ios::binary | ios::app);
JOKE j;
int n,i;
cout<<”How many objects you want to add :”;
cin>>n;
for (i=0;i<n;i++)
{
j.Newjokeentry();
afile.write((char *)& j, sizeof (JOKE));
}
afile.close();
}
Given a binary file TELEPHONE.DAT, containing records of the following class Directory
class Directory
{ char name[20],address[30], areacode[5], phone_no[15];
public:
void register();
void show();
int checkcode(char AC[ ]) { return strcmp(areacode, AC);}
};
Write a function COPYABC() in C++, that would copy all those records having areacode as
“123” from TELEPHONE.DAT to TELEBACK.DAT
COPYABC()
{ifstream ifile(“TELEPHONE.DAT”,ios::in|ios::binary);
If(!ifle) { cout<<”could not open TELEPHONE.DAT”; exit(-1);}
else
{ofstream ofile(“TELEBACK”,ios::out|ios::bainary);
if(!ofile) {cout<<”could not open TELEBACK.DAT”; exit(-1);}
else
{Directory d;
while(ifile.read((char *)&d, sizeof(d)))
{if(d.checkcode(“123”)==0)
Ofile.write((char *)&d,sizeof(d));
}
ifile.close();
ofile.close();
30
}
}
}
Exercise :3 Marks Question
2. Write a function in C++ to search for a BookNo from a binary file “BOOK.DAT”,
assuming the binary file is containing the objects of the following class.
class BOOK
{
int Bno;
char Title[20];
public:
int RBno(){return Bno;}
void Enter(){cin>>Bno;gets(Title);}
void Display(){cout<<Bno<<Title<<endl;}
};
3. Write a function in C++ to add new objects at the bottom of a binary file
“STUDENT.DAT”, assuming the binary file is containing the objects of the following
class.
class STUD
{int Rno;
char Name[20];
public:
void Enter()
{cin>>Rno;gets(Name);}
void Display(){cout<<Rno<<Name<<endl;}
};
31