/******************************************************************************* * * longest_line.c * * AUTHOR: * Dan Harkless * * COPYRIGHT: * This file is Copyright (C) 1999 by Dan Harkless, and is released under the * GNU General Public License . * * USAGE: * % longest_line [] * * DESCRIPTION: * Prints the length (including the trailing \n, if any) of the longest line in * the specified file (or stdin, if none specified). * * DATE MODIFICATION * ========== ================================================================== * 1999-04-09 Use strerror() to print exact error that occurs on unopened files. * 1996-11-19 Original. * *******************************************************************************/ #include /* for errno */ #include /* for fprintf(), etc. */ #include /* for strerror() and strrchr() */ int main(int argc, char** argv) { char c; char* last_slash = strrchr(argv[0], '/'); char* our_program_name; FILE* file; int i = 0, longest_line = 0; if (last_slash == NULL) our_program_name = argv[0]; else our_program_name = last_slash + 1; if (argc < 2) file = stdin; else if (argc > 2) { fprintf(stderr, "Usage: %s []\n", our_program_name); return 1; } else { file = fopen(argv[1], "r"); if (file == NULL) { fprintf(stderr, "%s: \"%s\": %s.\n", our_program_name, argv[1], strerror(errno)); return 1; } } while (!feof(file)) { c = fgetc(file); i++; if (c == '\n') { if (i > longest_line) longest_line = i; i = 0; } } printf("%d\n", longest_line); return 0; }