LAB 12 - File-Handling

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

LAB# 13: File handling

Description

Our program can interact to the outer world by taking input and displaying output. In/out of programs can
be taken from console or files. Console helps to interact with user in run time environment whereas
reading input from file and writing output to file helps in permanent storage of interaction history and
helps in simulation building.

1. Strings with Embedded Blanks

 Writing to File: Cannot use space as delimiter for separating multiple string in this case Use
some other delimiter instead of space

Example
void main()
{
ofstreamoutfile(“test.txt”);
outfile<<”I fear thee, ancient mariner!\n”; //here we use newline as delimiter
outfile<<”I fear thy skinny hand\n”;
outfile<<”And thou art long, and lank, and brown, \n”;
outfile<<”As is the ribbed sea sand, \n”;
}

 Reading from File: Cannot use extraction operator for reading Use getline() member function of
istream class to read string from file (remember, ifstream is derived from istream).

Example
void main()
{
char buffer[MAX]; //create a buffer to hold individual strings max size is
100
ifstreaminfile(“test.txt”); //open file
while (infile.eof() != true) //check for end of file
{
infile.getline(buffer,MAX); //getline reads chars into buffer till end of line
cout<<buffer<<endl; //display the string
}
}

Lab Tasks:

I. You are the owner of a hardware store and need to keep an inventory that can tell you what
different tools you have, how many of each you have on hand and the cost of each one. Write a
program that initializes the random-access file "hardware .txt " to one hundred empty records, lets
you input the data concerning each tool, enables you to list all your tools, lets you delete a record
for a tool that you no longer have and lets you update any information in the file. Thetool
identification number should be the record number. Use the following information to start your
file:

Record # Tool Name Quantity Cost

3 Electric sandel 7 456

17 Hammer 76 321

24 Jigsaw 21 897

39 Lawn mover 56 3333

56 Power saw 3 121

68 Screw driver 17 653

77 Wrench 54 12

[HINT: You can create a class to initialize Tools and object of that class to be written in file]

II. In a loop, prompt the user to enter its data consisting of a first name, last name and employee
number. Then using, ofstream object write these three data items in a file. Don’t forget that
strings must be terminated with a white space. When all the data is written, close the ofstream
object, open an ifstream object, read and display all data in the file and terminate the program.

Write the following line of code in a file as follows

My name is Ali.

I live in Rawalpindi.

I study at Air.

You might also like