File Handling 2
File Handling 2
#include<iostream>
#include<fstream>
using namespace std;
main()
{
int id,qty,price;
string name;
cout<<"Enter the Item ID:";
cin>>id;
cout<<"\nEnter the Item Name:";
cin>>name;
cout<<"\tEnter the Quantity:";
cin>>qty;
cout<<"\nEnter the Price:";
cin>>price;
ofstream fout("Item.txt",ios::app);
fout<<id<<"\t"<<name<<"\t"<<qty<<"\t"<<price<<endl;
fout.close();
string irecord;
ifstream fin("Item.txt");
while(getline(fin,irecord))
{
cout<<irecord<<endl;
}
fin.close();
return 0;
}
Q: WA C++ program to write Item record (i.e. also for append Item record) and display entire
Item records (i.e. read Item record) from the file named i.e. Item.txt.
#include<iostream>
#include<fstream>
using namespace std;
main()
{
int id,qty,price;
char name[20];
cout<<"Enter the Item ID:";
cin>>id;
cout<<"\nEnter the Item Name:";
cin>>name;
cout<<"\tEnter the Quantity:";
cin>>qty;
cout<<"\nEnter the Price:";
cin>>price;
ofstream fout("d:/Item1.txt",ios::app);
fout<<id<<"\t"<<name<<"\t"<<qty<<"\t"<<price<<endl;
fout.close();
char irecord[32];
ifstream fin;
fin.open("d:/Item1.txt");
//while(getline(fin,irecord))
while(fin.getline(irecord,32))
{
cout<<irecord<<endl;
}
fin.close();
return 0;
}
Q: WA C++ menu driven program to write Item record (i.e. also for append Item record) and
display entire Item records (i.e. read Item record) from the file named i.e. Item.txt.
#include<iostream>
#include<fstream>
#include<process.h>
using namespace std;
void writeData()
{
int id,qty,price;
string name;
cout<<"Enter the Item ID:";
cin>>id;
cout<<"\nEnter the Item Name:";
cin>>name;
cout<<"\nEnter the Quantity:";
cin>>qty;
cout<<"\nEnter the Price:";
cin>>price;
ofstream fout("Item.txt",ios::app);
fout<<id<<"\t"<<name<<"\t"<<qty<<"\t"<<price<<endl;
fout.close();
}
void readData()
{
string irecord;
ifstream fin("Item.txt");
while(getline(fin,irecord))
{
cout<<irecord<<endl;
}
fin.close();
}
main()
{
string irecord;
int ch;
while(1)
{
cout<<"1.Write \t 2.Read \t3.Exit\n";
cout<<"Enter your choice:";
cin>>ch;
switch(ch)
{
case 1:
writeData();
break;
case 2:
readData();
break;
case 3: exit(0);
default: cout<<"Enter Correct choice:";
}
return 0;
}
Q: WA C++ program to read and write from the file named i.e. student.doc. Use fstream class and
member function open() .
#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
cout<<"\nEnter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;
fstream file;
file.open("d:/student.doc",ios::out);
file<<rno<<"\t"<<name<<"\t"<<fee; //write data to the file student
file.close();
file.open("d:/student.doc",ios::in);
file>>rno>>name>>fee; //read data from the file student
file.close();
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
return 0;
}
The !(logical negation operator) is useful for detecting the errors. It is a unary operator and in
short it is called as not operator. The not operator can be used with object of stream class. This
operator returns non-zero value if stream errors are found during operation.
Q: Write a program to check whether the file is successfully opened or not.
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
int rno,fee;
char name[50];
char fname[50];
fstream file;
file.open(fname,ios::in);
if(!file)
{
cout<<"\nError in opening file:\t"<<fname;
getch();
}
file.close();
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
return 0;
}
To avoid this, it is necessary to provide correct instruction to the program that detects the end of file. Thus
the end of file is detected; the process of reading data can be easily terminated.
The eof() member function is used for this purpose. The eof() stands for end of file. The eof() function
returns non-zero value when end of file is detected, otherwise zero.
Q: Write a C++ program to read and display the content of file. Use eof() member function.
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
char ch;
fstream file;
file.open("d:/student.doc",ios::in);
if(!file)
{
cout<<"\nError in opening file:\t"<<"student.doc";
getch();
}
while(file.eof()==0)
{ // function get() reads a single character from the associated stream.
file.get(ch); // or ch=file.get();
cout<<ch;
}
file.close();
return 0;
}
Question: Write a program to detect end of the file using function eof(). Display the values returned by
the eof()function.
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
char ch;
fstream file;
file.open("d:/student.doc",ios::in);
if(!file)
{
cout<<"\nError in opening file:\t"<<"student.doc";
getch();
}
while(file.eof()==0)
{ // function get() reads a single character from the associated stream.
file.get(ch); // or ch=file.get();
cout<<file.eof();
}
file.close();
return 0;
}
Question: Write a C++ program to count the number of words and lines in a file.
#include<iostream>
#include<fstream>
using namespace std;
main()
{
char str[100];
ifstream fin;
fin.open("e:/str.doc");
if(!fin)
{
cout<<"File Not Found/Opened";
return 0;
}
char ch;
int word=0,line=0;
fin.seekg(0,ios::beg);
while(fin.eof()==0)
{
ch=fin.get();
if(ch==' ')
word++;
if(ch=='\n')
line++;
cout<<ch;
}
cout<<"\nTotal Word:"<<word;
cout<<"\nTotal Line:"<<line;
fin.close();
return 0;
}
Q: Write a C++ program to count the number of alphabets, digit and spaces present in a file.
#include<iostream>
#include<fstream>
using namespace std;
main()
{
char str[100];
cout<<"Enter the String:";
gets(str);
ofstream fout;
fout.open("e:/str1.doc");
int i;
for(i=0;str[i]!='\0';i++)
fout.put(str[i]);
fout.close();
ifstream fin;
fin.open("e:/str1.doc");
if(!fin)
{
cout<<"File Not Found/Opened";
return 0;
}
char ch;
int a=0,d=0,s=0;
fin.seekg(0,ios::beg);
while(fin.eof()==0)
{
ch=fin.get();
i=ch;
if((i>=65 && i<=90)||(i>=97 && i<122))
a++;
if(i>=47 && i<=58)
d++;
if(ch==' ')
s++;
cout<<ch;
}
cout<<endl<<"No. OF Alphabates:"<<a;
cout<<endl<<"No. Of Digits:"<<d;
cout<<endl<<"No. Of Spaces:"<<s;
fin.close();
return 0;
}
Q: Write a C++ program to read data from a text file and then write in another text file.
int main()
{
ofstream fout;
fout.open(“file_1.txt”); //create a file_1 to write
ifstream fin(“file_1.txt”);
fout<<“Hello India”;
fout.close(); //closing the file
while(fin.eof()==0)
{
fin.get(ch); //reading data from file_1
if(fin.eof()==1)
break;
fout<<ch; //writing data to file_2
}
fin.close();
fout.close();
return 0;
}
The input pointer is used for reading the contents of a given file location and the output pointer is used for
writing to a given file location.
Default Action
--------------------
When we open a file in read only mode, the input pointer is automatically set at the beginning so that we
can read the file from the start.
Similarly when we open a file in write only mode, the existing contents are deleted and the output pointer
is set at beginning.
In case, we want to open an existing file to add more data, the file is opened in append mode. This
moves the output pointer to the end of the file.
“Demo” file
Input pointer
Output pointer
Manjeet kumar
seekg() This function moves the “get” pointer to a specified location to do a read operation.
tellg() This function tells the current position of the “get” pointer in the file.
seekp() This function moves the “put” pointer to a specified location to do a write operation.
tellp() This function tells the current position of the “put” pointer in the file.
Eg:
ifstream fin(“temp.doc”);
fin.seekg(10);
The bytes in a file are numbered beginning from zero. Therefore, the pointer will be pointing to the 11 th
byte in the file.
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
char str[100],ch;
int i;
cout<<"Enter the String:";
cin.getline(str,100);
ofstream fout;
fout.open("d:/Demo.doc",ios::ate);
for(i=0;str[i]!='\0';i++)
fout.put(str[i]);
fout.close();
ifstream fin;
fin.open("d:/Demo.doc",ios::ate);
while(fin.eof()==0)
{
ch=fin.get();
cout<<ch;
}
fin.close();
return 0;
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
char str[100],ch;
int i;
cout<<"Enter the String:";
cin.getline(str,100);
ofstream fout;
fout.open("d:/Demo.doc",ios::ate);
for(i=0;str[i]!='\0';i++)
fout.put(str[i]);
fout.close();
ifstream fin;
fin.open("d:/Demo.doc",ios::ate);
cout<<endl<<"Number of byte="<<x;
fin.close();
return 0;
On execution of this statement, the input pointer is moved to the end of the file “Demo.doc” and the
value of ‘x’ will represent the number of bytes in the file.
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
char str[100],ch;
int i;
ofstream fout;
fout.open("d:/Demo.doc",ios::app|ios::ate);
fout.seekp(8);
fout<<"kumar";
fout.close();
ifstream fin;
fin.open("d:/Demo.doc",ios::ate);
cout<<endl<<"Number of byte="<<x<<endl;
fin.seekg(0);
while(fin.eof()==0)
{
char ch=fin.get();
cout<<ch;
}
fin.close();
return 0;
}
Specify the offset
----------------------
We have seen how to move a file pointer to desired location using the seek function. The argument to
these functions represents the absolute position in the file.
file
Start end
fin.seekg(m);
m bytes
file pointer
“seek” function seekg() and seekp() can also be used with two arguments as follows:
seekg(offset, refposition) ;
seekp(offset, refposition);
The parameter offset represents the number of bytes the file pointer is to be moved from the location
specified by the parameter refposition. The refposition takes one of the following three constants defined
in the “ios” class.
Example:
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
char str[100],ch;
int i;
cout<<"Enter the String:";
cin.getline(str,100);
ofstream fout;
fout.open("d:/Demo.docx", ios::out|ios::ate|ios::binary);
for(i=0;str[i]!='\0';i++)
fout.put(str[i]);
fout.close();
ifstream fin;
fin.open("d:/Demo.docx");
fin.seekg(7,ios::beg); //move 8 bytes from the beg.
while(fin.eof()==0)
{
ch=fin.get();
cout<<ch;
}
fin.close();
return 0;
}
Q: Write a program to write text in the file. Read the text from the file from end of file. Display the
contents of file in reverse order.
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
char str[100],ch;
int i;
cout<<"Enter the String:";
cin.getline(str,100);
ofstream fout;
fout.open("d:/Demo.doc", ios::out|ios::ate|ios::binary);
for(i=0;str[i]!='\0';i++)
fout.put(str[i]);
fout.close();
ifstream fin;
fin.open("d:/Demo.doc");
fin.seekg(0,ios::end); //move the cursor to the end of file
int m=fin.tellg();
for(i=1;i<=m;i++)
{
fin.seekg(-i,ios::end);
ch=fin.get();
cout<<ch;
}
fin.close();
return 0;
}
Sequential input and output operation
------------------------------------------------
File stream classes support a number of member functions for performing the input and output operations
on files. One pair of functions, put() and get() are designed for handling a single character at a time.
Another pair of functions, write() and read() are designed to write and read blocks of binary data.
The function put() writes a single character to the associated stream. Similarly the function get() reads a
single character from the associated stream.
Example:
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
char str[100],ch;
int i;
cout<<"Enter the String:";
cin.getline(str,100);
ofstream fout;
fout.open("d:/Demo.doc", ios::out|ios::ate|ios::binary);
for(i=0;str[i]!='\0';i++)
fout.put(str[i]); //put a character to a file
fout.close();
ifstream fin;
fin.open("d:/Demo.doc");
while(fin.eof()==0)
{
ch=fin.get(); //get a character from a file
cout<<ch; //display it on screen
}
fin.close();
return 0;
}
write() and read() functions
----------------------------------
The functions write() and read(), unlike the function put() and get(), handle the data in binary form. This
means that the values are stored in the disk file in the same format in which they are stored in the internal
memory.
Example:
The ‘int’ value 2594 is stored in the binary and character format. The ‘int’ takes two bytes to store its
value in the binary format, irrespective of it’s size. But a 4 digit int value will take 4 bytes to store it in
character format.
2 bytes
Character format 2 5 9 4
4 bytes
The binary format is more accurate for storing the numbers as they are stored in the exact internal
representation. There are no conversions while saving the data and therefore saving is much faster.
The binary input and output functions take the following form:
file.write((char *)&v,sizeof(v));
These functions takes two argument, the first is the address of the variable ‘v’ and the second is the length
of that variable in bytes. The address of the variable must be cast to type char *(i.e. pointer to char).
#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
cout<<"\nEnter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;
ofstream fout;
fout.open("d:/student.doc");
fout.write((char*)&rno,sizeof(rno));
fout.write((char*)&name,sizeof(name));
fout.write((char*)&fee,sizeof(fee));
fout.close();
ifstream fin;
fin.open("d:/student.doc");
fin.read((char*)&rno,sizeof(rno));
fin.read((char*)&name,sizeof(name));
fin.read((char*)&fee,sizeof(fee));
fin.close();
cout<<"\nRoll No:\t"<<rno<<endl;
cout<<"\nName:\t"<<name<<endl;
cout<<"\nFee:\t"<<fee<<endl;
return 0;
}
#include<iostream>
#include<fstream>
using namespace std;
class Student
{
int rno,fee;
char name[50];
public:
void set_data()
{
cout<<"\nEnter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;
}
void display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
};
main()
{
int i,no;
Student s[10];
cout<<"\nEnter Number of Student:";
cin>>no;
ofstream fout;
fout.open("d:/Student.doc");
ifstream fin;
fin.open("d:/Student.doc");
if(!fin)
{
cout<<"\nFile not found.";
return 0;
}
for(i=0;i<no;i++)
{
fin.read((char*)&s[i],sizeof(s[i]));
s[i].display();
}
fin.close();
return 0;
}
Q. Create a class to specify data on students given below:
Write a menu driven program in C++ for following operations on student class such as Add,
Display all record, Search record by given roll number and Delete record by given roll number
from the file.
#include<iostream>
#include<conio.h>
#include<process.h>
#include<fstream>
#include<stdio.h>
void deletedata(int);
void search(int);
class stud
public:
int rno;
char name[20];
public:
void getdata()
cin>>rno;
fflush(stdin);
cin>>name;
void display()
{
cout<<endl<<rno<<"\t"<<name<<endl;
};
main()
int i,chk;
char chk1;
char ch;
stud s;
fstream file,temp;
ofstream fout1;
ifstream fin;
// fout.open("b.dat",ios::in|ios::out|ios::ate|ios::binary);
while(1)
cin>>chk;
switch(chk)
case 1:
cout<<"\nADD SUTUDENT DETAILS\n";
fout1.open("d:/student.docx",ios::app| ios::binary);
s.getdata();
fout1.write((char*)&s,sizeof(s));
fout1.close();
fin.open("d:/student.docx");
if(!fin)
getch();
exit(0);
while(fin.read((char*)&s,sizeof(s)))
s.display();
fin.close();
break;
case 2:
cout<<"\nCURRENT INFORMATION\n";
fin.open("d:/student.docx",ios::in);
while(fin.read((char*)&s,sizeof(s)))
s.display();
fin.close();
break;
cin>>rno1;
deletedata(rno1); break;
case 5:
int rno2;
cin>>rno2;
search(rno2); break;
case 6: exit(0);
case 3:
ofstream fout;
fout.open("d:/student.docx",ios::out|ios::ate|ios::binary);
if(!fout)
getch();
exit(0);
}
int last=fout.tellp();
cout<<"-----------"<<last;
int n=last/sizeof(s);
int obj;
cin>>obj;
int location=(obj-1)*sizeof(s);
fout.seekp(location);
//file.close();
// file.open("student.doc",ios::out|ios::ate);
s.getdata();
fout.write((char*)&s,sizeof(s));
fout.close();
fin.open("d:/student.docx");
fin.seekg(0);
while(fin.read((char*)&s,sizeof(s)))
s.display();
fin.close();
break;
getch();
return 0;
stud s;
fstream file,temp;
file.open("d:/student.docx",ios::in);
temp.open("d:/temp_student.docx",ios::out);
file.seekg(0);
//while(!file.eof())
//{
while(file.read((char *)&s,sizeof(s)))
if(s.rno!=rno1)
temp.write((char *)&s,sizeof(s));
file.close();
temp.close();
file.open("d:/student.docx",ios::out);
temp.open("d:/temp_student.docx",ios::in);
temp.seekg(0);
//while(!temp.eof())
//{
while(temp.read((char *)&s,sizeof(s)))
//if(temp.eof())
// break;
file.write((char *)&s,sizeof(s));
file.close();
temp.close();
}
void search(int rno1)
ifstream file;
file.open("d:/student.docx");
int rno;
stud s;
if(!file)
getch();
exit(0);
file.seekg(0);
while(file.read((char *)&s,sizeof(s)))
if(s.rno==rno1)
s.display();
//cout<<endl<<s.rno<<" "<<s.name;
file.close();