/* This is the line count program I coded up in Lecture 08. * 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. * This program is incomplete, and even generates a compiler warning. * A complete version will be posted with Lecture 09. */ #include // standard library stuff for printing and file I/O // during compilation MAX_LINE_LENGTH will get replaced with 500 #define MAX_LINE_LENGTH 500 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 lines = count_lines(file); // compiler warning on this line since we haven't declared count_lines beforehand // could use fprintf(stdout, ...) to print to stdout, but printf is easier printf("%i\n", lines); // %i 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; } } int count_lines(FILE *file) { int 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++; } return count; }