Sams Teach Yourself C in 21 Days

(singke) #1
626 Week 3

would handle such a failure, but I omitted it here to keep the program from getting too
long. Line 119 writes the data to the disk file with a call to fwrite().
The report feature in this program also has changed. One feature typical of most “real-
world” reports is the inclusion of the current date and time at the top of the report. On
line 137, the variable rtimeis declared. This variable is passed to time()and then dis-
played using the ctime()function. These time functions were presented on Day 19,
“Exploring the C Function Library.”
Before the program can start printing the records in the file, it needs to reposition the file
pointer at the beginning of the file. This is done on line 145 with another call to fseek().
after the file pointer is positioned, records can be read one after the other. Line 147 does
the first read. If the read is successful, the program begins a whileloop that continues
until the end of the file is reached (when feof()returns a nonzero value). If the end of
the file hasn’t been reached, line 150 prints the information, line 153 counts the record,
and line 154 tries to read the next record. You should notice that functions are used with-
out checking their return values in order to keep the program a reasonable length. To
protect the program from errors, the function calls should contain checks to ensure that
no errors occurred.
One function in the program is new. Lines 200–234 contain the function look_up(),
which searches the disk file for all records that contain a certain last name. Lines 205
and 206 prompt for the name to be found and store it in a local variable called
tmp_lname. If tmp_lnameisn’t blank (line 208), the file pointer is set to the beginning of
the file. Each record is then read. Using strcmp()(line 215), the record’s last name is
compared to tmp_lname. If the names match, the record is printed (lines 218–222). This
continues until the end of the file is reached. Again, you should notice that not all the
functions have their return values checked. You should always check return values.
You should be able to modify this program to create your own files that can store any
information. Using the functions you learned during Week 3, along with the other func-
tions in the C library, you should be able to create a program to do just about anything
you want.

34 448201x-W3R 8/13/02 11:22 AM Page 626

Free download pdf