|
CS256 - Fundamentals of Structured Programming
| Displaying exercises/e9/solution/f1.c
#include <stdio.h>
#define K 1024
/**
* Make a program that takes a filename from the command line, or print the
* usage message: "Usage: f1 <filename>\n" if it's absent.
* Open the file and print it out with a leading line number padded to three
* spaces. Hint: It would probably be easiest to use fgets to read each line
* of input from the file.
*/
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("Usage: f1 <filename>\n");
return 1;
}
FILE *fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
char buf[K];
int line = 1;
while(fgets(buf, K, fp) != NULL) {
printf("%3d %s", line, buf);
line++;
}
fclose(fp);
return 0;
}
|