Files in C
Goals: This laboratory provides experience retrieving data from
text files using C.
Text Data File
The file ~walker/151p/labs/lab26.dat contains several items of
information about large American cities. More specifically, in
~walker/151p/labs/lab26.dat, each entry consists of the
name of the city (line 1), the county or counties (line 2) and the state
(line 3) in which it is situated, the year in which it was incorporated
(line 4), its population as determined by the census of 1980 (line 5), its
area in square kilometers (line 6), an estimate of the number of telephones
in the city (line 7), and the number of radio stations (line 8) and
television stations (line 9) serving the city. Thus a typical entry reads
as follows:
Albuquerque
Bernalillo
New Mexico
1891
331767
247
323935
14
5
A blank line follows each entry, including the last.
-
Copy the file to your account and display
it at your workstation (using the type command). Also, observe that
you can edit this file by using an editor, such as xemacs or vi.
-
Several later parts of this lab will involve using
these data by expanding a program
~walker/c/files.c . Copy this program to you account,
compile it, and run the program. Then review how the
program works, so that you can answer the following questions.
Work to turn in:
-
How does the program know which file to read?
-
How is each line of text read?
-
What does procedure readLine do?
-
Why is readLine used in
readCity for city.nme, while fscanf is
used for city.yar?
-
Why do you think readLine is defined?
-
How might this program differ if data
were being read from the keyboard rather than from a file? How could
this program be changed so it reads data from a different data file?
Processing Data in Files
Consider the following questions about the cities represented in the data
files:
-
Which of these cities listed in the file were incorporated
more than 150 years ago?
-
Which of these cities has the highest population density
(population divided by area)?
-
Which of these cities has more than 1 million telephones?
-
Which of these cities has the lowest per capita number of radio and
TV stations?
Program file.c contains stubs for procedures for these questions.
-
Fill in the details for procedure incorporated,
which will scan the entire text file and print out the data on each city
that was incorporated more than 150 years ago. This will answer question a.
-
Answer question b by filling in the details for procedure
population.
-
Fill in the details of procedure telephone to answer question c.
-
Answer question d by providing the code for procedure media.
Work to turn in:
-
Print out the expanded program, containing details of both of these
procedures, and test it thoroughly.
This document is available on the World Wide Web as
http://www.cs.grinnell.edu/~walker/courses/195.fa01/lab.files.html