0% found this document useful (0 votes)
6 views

File Handling 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

File Handling 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 29

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;
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;
}

Checking for errors


----------------------------
When the user attempts to read file that does not exists or opens a read only file for writing purpose, in
such situation operation fails. Such errors must be reported and proper actions have to be taken before
further operation.

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];

cout<<"\nEnter the File Name:";


cin>>fname;

fstream file;
file.open(fname,ios::in);

if(!file)
{
cout<<"\nError in opening file:\t"<<fname;
getch();
}

file>>rno>>name>>fee; //read data from the file student

file.close();

cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;

return 0;
}

Finding end of a file


---------------------------
While reading a data from a file, it is necessary to find whether the file end i.e end of the file. The
programmer cannot predict the end of a file. In a program while reading the file, if the program does not
detect the end of the file, the program drops in an infinite loop.

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

fout.open(“file_2.txt”); //create file_2 to write


char ch;

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;
}

File pointers and there manipulation


----------------------------------------------
Each file has two associated pointers known as file pointers. One of them is called the input pointer or get
pointer and other is called the output pointer or put pointer. We can use these pointers to move through
the files while reading and writing.

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.

This enables us to write to file from the start.

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

Open for read only M A N J E E T

Input pointer

Open for writing only M A N J E E T

Output pointer

Open in append mode M A N J E E T

(for writing more data) Output pointer

Fig: Action on file pointers while opening a file

File pointer manipulation function


-------------------------------------------
If the user wants to move the file pointers at desired locations in the file during run-time to perform
various operations. For this purpose, we have 4 file pointer manipulation functions. Among them 2 are
dedicated to “put” pointer and 2 are dedicated to “get” 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);

Moves the file pointer to the byte number 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);

fin.seekg(7);// move 8 bytes from the beginning

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);

int x=fin.tellg();// tells the current position in the file

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);

int x=fin.tellg();// tells the current position in the file

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

Fig: Action of single argument seek function

“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.

1. ios::beg  start of the file

2. ios::cur  current position of the pointer

3. ios:end end of the file

seek call Action

fin.seekg(0, ios::beg); Go to start

fin.seekg(0, ios::cur); Stay at the current position

fin.seekg(0, ios::end); Go to the end of file

fin.seekg(m, ios::beg); Move to (m+1)th byte in a file

fin.seekg(m, ios::cur); Go forward by ‘m’ byte from the current position


fin.seekg( -m, ios::cur); Go backward by ‘m’ bytes form the current
position

fin.seekg( -m, ios::end); Go backward by ‘m’ bytes from the end.

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.

put() and get() functions


------------------------------

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

Binary format 00001010 00100010

Character format 2 5 9 4

4 bytes

Fig - Binary and character format of an integer value.

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.read((char *)&v, sizeof(v));

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;
}

Reading and Writing a class object

#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");

cout<<"\nEnter the Student details one by one:";


for(i=0;i<no;i++)
{
s[i].set_data();
fout.write((char*)&s[i],sizeof(s[i]));
}
fout.close();

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:

Roll number, Name, Department, and Course.

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>

using namespace std;

void deletedata(int);

void search(int);

class stud

public:

int rno;

char name[20];

public:

void getdata()

cout<<"\nEnter the rno:";

cin>>rno;

fflush(stdin);

cout<<"Enter the name:";

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)

cout<<"\n1.ADD\n2.DISPLAY CURRENT RECORD\n3.UPDATE RECORD\n4.DELETE\


n5.SEARCH\n6.Exit";

cout<<"\nEnter the choice:";

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)

cout<<"Error in opening file.";

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;

case 4: int rno1;

cout<<"\nenter the rno to delete the record:";

cin>>rno1;

deletedata(rno1); break;

case 5:

int rno2;

cout<<"\nEnter the rno to search:";

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)

cout<<"Error in opening file.";

getch();

exit(0);
}

int last=fout.tellp();

cout<<"-----------"<<last;

int n=last/sizeof(s);

cout<<"\nTotal Number of Record:"<<n;

cout<<"\nEnter the record number to be updated:";

int obj;

cin>>obj;

int location=(obj-1)*sizeof(s);

fout.seekp(location);

//file.close();

// file.open("student.doc",ios::out|ios::ate);

cout<<"\nEnter the new record\n";

s.getdata();

fout.write((char*)&s,sizeof(s));

fout.close();

fin.open("d:/student.docx");
fin.seekg(0);

cout<<"\n CONTENT OF THE UPDATED FILE\n";

while(fin.read((char*)&s,sizeof(s)))

s.display();

fin.close();

break;

getch();

return 0;

void deletedata(int rno1)

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)

cout<<"Error in opening 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();

You might also like