Sams Teach Yourself C in 21 Days

(singke) #1
smart enough to recognize them as errors and report them to you. (You saw in yester-
day’s material how the compiler reports error messages and how you interpret them.)

A Review of the Parts of a Program ....................................................................


Now that all the parts of a program have been described, you should be able to look at
any program and find some similarities. Look at Listing 2.2 and see whether you can
identify the different parts.

LISTING2.2 list_it.c—A program to list a code listing
1: /* list_it.c__This program displays a listing with line numbers! */
2: #include <stdio.h>
3: #include <stdlib.h>
4:
5: void display_usage(void);
6: int line;
7:
8: int main( int argc, char *argv[] )
9: {
10: char buffer[256];
11: FILE *fp;
12:
13: if( argc < 2 )
14: {
15: display_usage();
16: return 1;
17: }
18:
19: if (( fp = fopen( argv[1], “r” )) == NULL )
20: {
21: fprintf( stderr, “Error opening file, %s!”, argv[1] );
22: return(1);
23: }
24:
25: line = 1;
26:
27: while( fgets( buffer, 256, fp ) != NULL )
28: fprintf( stdout, “%4d:\t%s”, line++, buffer );
29:
30: fclose(fp);
31: return 0;
32: }
33:
34: void display_usage(void)
35: {
36: fprintf(stderr, “\nProper Usage is: “ );
37: fprintf(stderr, “\n\nlist_it filename.ext\n” );
38: }

36 Day 2

05 448201x-CH02 8/13/02 11:14 AM Page 36

Free download pdf