/* * program to print a file with file name and line number * prefixing each line * invocation: * num print stdin with line numbers * num arg1 ... print contents of arg1 with line numbers * exit code: number of files not opened * author: Matt Bishop, bishop@cs.ucdavis.edu, 9/16/96 */ #include #include /* * print the given file, with the file name and line * number in front * arguments: fn pointer to file name * fp file pointer */ void cat(char *fn, FILE *fp) { register int c; /* input character */ register int lno = 0; /* line number */ register int nlstate = 1; /* 1 if last char was newline */ /* * read the file */ while((c = getc(fp)) != EOF){ /* was the previous char a newline */ if (nlstate){ /* one more line */ lno++; /* print the line number and file name */ if (fn == NULL) printf("%4d: ", lno); else printf("%s,%4d: ", fn, lno); /* we now clear the record of the newline */ nlstate = 0; } /* print the character */ putchar(c); /* if it's a newline, set the flag */ if (c == '\n') nlstate = 1; } } /* * the main routine */ int main(int argc, char *argv[]) { register int nerr = 0; /* nuber of files not opened */ register char **a; /* used to walk argument list */ register FILE *fp; /* pointer to file being processed */ /* * no argument -- use stdin */ if (argc == 1){ cat(NULL, stdin); return(EXIT_SUCCESS); } /* * walk the arg list, doing each file */ for(a = &argv[1]; *a != NULL; a++) /* open the file */ if ((fp = fopen(*a, "r")) == NULL){ /* oops ... say what happened */ perror(*a); nerr++; } else{ /* print the file */ cat(*a, fp); } /* * status is the number of files not opened */ return(nerr); }