/* * PRINTLINE3 -- Argument(s) is/are file name(s) and print each on the standard output * each line prefixed by the line number * this version uses fgets and fputs (last prints line directly) * * Usage: printfile3 * * Inputs: file names; EOF to exit * Output: contents of file, each line prefixed by line number * Exit Code: number of files it could not open * * Matt Bishop, ECS 36A, Fall 2019 * * Oct. 22, 2015 -- original program written * Oct. 23, 2019 -- modified for ECS 36A */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* * useful macros */ #define MAXFILENAMESIZE 1024 /* maximum length of file name */ #define MAXLINELENGTH 1000 /* maximum line length */ /* * COPYOUT -- copy the contents of a file to standard output using fputs * * parameters: FILE *fp pointer to file to be copied out * return: none * assumptions: fp points to a file * side effects: prints the line number followed by tab followed by line */ void copyout(FILE *fp) { char buf[MAXLINELENGTH]; /* buffer to hold line */ static int lineno = 1; /* current line number */ /* * read until done */ while(fgets(buf, MAXLINELENGTH, fp) != NULL){ /* not done yet so print line number, then line */ printf("%6d\t", lineno++); fputs(buf, stdout); } } /* * read a file name from the standard input, * open it, and print it with line numbers * before each line */ int main(int argc, char *argv[]) { FILE *fp; /* file pointer */ int rv = 0; /* number of files that couldn't be opened */ int i; /* counter in a for loop */ /* * read one file name per line, and do the dirty deeds * then get the next one, -, until EOF */ for(i = 1; i < argc; i++){ /* open the file */ if ((fp = fopen(argv[i], "r")) == NULL){ fprintf(stderr, "Could not open file %s\n", argv[i]); rv++; continue; } /* copy the file, putting line numbers in front of each line */ copyout(fp); /* now close it */ (void) fclose(fp); } /* * say goodbye! */ exit(rv); }
|
ECS 36A, Programming & Problem Solving Version of April 2, 2024 at 12:13PM
|
You can get the raw source code here. |