Notes
Outline
COM1100
Fundamentals of Computer Science –Winter 2000
Lecture 21
03/02/00
Lecture today
File stream as function arguments
Examples of reading and writing text file
Declare file stream variable
Open a file by indicating its name
Get data from a file
Write data into a file
Close a file
File stream as function arguments
A file stream object can be a function argument.
The only requirement is that the function’s formal parameter be a reference to the appropriate stream, either as :
ifstream&
or ofstream&
Example 1 – ifstream&
Write a function GetInputFile that will receive one input file stream as argument, and will open the file stream by asking the user to enter a file name.
Example 2 – ofstream&
Write a function GetOutputFile that will receive one output file stream as argument, and will open the file stream by asking the user to enter a file name.
Question 1
Suppose there is a data file PaintData.txt with the following contents:
circle 100 100 20
rectangle 40 40 90 80
rectangle 140 140 190 180
circle 200 200 50
The first column in each line is a label.
If the label is equal to “circle”, then the following data in this line are xcenter, ycenter and radius for painting a circle.
If the label is equal to “rectangle”, then the following data in this line are x1, y1, x2 and y2 for painting a rectangle.
Read all the data from the file and paint either circls or rectangle according to the corresponding labels.
Question 1  -- Solution
ifstream myFile; // declare an input file stream
GetInputFile(myFile); // call function GetInputFile (see slide 4)
  int x1, y1, x2, y2; // declare variables for rectangle
int xcenter, ycenter, r; // declare variables for circle
string label; // declare variable for label
  while (myFile.peek() != EOF) { // test if at the End Of File (EOF)
myFile >> label; // read label
if (label == "circle") {
myFile >> xcenter >> ycenter >> r; // read xcenter, ycenter and r
PaintCircle(xcenter,ycenter,r); // paint a circle
}
else if (label =="rectangle") {
myFile >> x1 >> y1 >> x2 >> y2; // read x1, y1, x2, y2
PaintRect(x1,y1,x2,y2); // paint a rectangle
}
}
 myFile.close(); // close the file stream
Question 2 and solution
Question 3 and solution
Question 4
Question 4 -- solution