/* This is the complete line count program from Lecture 09. * It shows how a simple C program is laid out, including taking command-line * arguments, printing to stdout and stderr, and reading from a file. */ #include // standard library stuff for printing and file I/O #include // standard library string functions // during compilation MAX_LINE_LENGTH will get replaced with 500 #define MAX_LINE_LENGTH 500 // prototype for count_lines, so main can use it int count_lines(FILE *file, int *c_count); int main(int argc, char **argv) { // we expect exactly two arguments // argv[0] is the command (i.e., "./line_count") // argv[1] FILE if (argc != 2) { // use fprintf to print to stderr fprintf(stderr, "usage: ./line_count FILE\n"); return 1; // exit status of 1 indicates error } FILE *file = fopen(argv[1], "r"); // try to open the file in "read" mode // check if we were able to open the file (fopen returns NULL if it fails) if (file != NULL) { int c_count; // character count int lines = count_lines(file, &c_count); // pass &c_count so count_lines can modify the value of c_count if (lines == -1) { // -1 indicates an error while reading fprintf(stderr, "line_count: error reading %s\n", argv[1]); return 3; } // could use fprintf(stdout, ...) to print to stdout, but printf is easier printf("%d %d\n", lines, c_count); // %d is the format string for an int return 0; // exit status of 0 for success } else { // %s is the format string for a string fprintf(stderr, "line_count: error opening %s\n", argv[1]); return 2; } } /* * Reads file and returns the number of lines. * Lines are assumed to be at most MAX_LINE_LENGTH characters long. * The number of characters in the file is stored in c_count */ int count_lines(FILE *file, int *c_count) { int count = 0; *c_count = 0; char line[MAX_LINE_LENGTH]; // will get turned into char line[500] at compilation /* fgets reads up to MAX_LINE_LENGTH characters from file and stores them in line, stopping at newlines * file keeps track of what has been read, so the next call to fgets will pick up where it left off * if successful, fgets returns line, which gets treated as true * if it fails (e.g., there are no more characters to read), fgets returns NULL, which gets treated as false */ while(fgets(line, MAX_LINE_LENGTH, file)) { count++; *c_count += strlen(line); } return count; }