/* * PRINTLINE2 -- Read a file name and print it on the standard output * each line prefixed by the line number * this version uses fgets and fputc, looping through the array * * Usage: printfile1 * * 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 * * written for ECS 030, Fall 2015 * * Matt Bishop, Oct. 16, 2015 * original program written */ #include #include #include /* * 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 * * 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 */ int i; /* counter in a for loop */ 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++); /* use a for loop to demonstrate sequential access */ for(i = 0; buf[i] != '\0'; i++) putchar(buf[i]); } } /* * read a file name from the standard input, * open it, and count characters, words, and lines */ int main(void) { char fname[MAXFILENAMESIZE]; /* the file name(s) */ FILE *fp; /* file pointer */ int rv = 0; /* number of files that couldn't be opened */ /* * read one file name per line, and do the dirty deeds * then get the next one, -, until EOF */ while(printf("file name> "), fgets(fname, MAXFILENAMESIZE, stdin) != NULL){ /* clobber trailing newline */ if (fname[strlen(fname)-1] == '\n') fname[strlen(fname)-1] ='\0'; /* open the file */ if ((fp = fopen(fname, "r")) == NULL){ fprintf(stderr, "Could not open file %s\n", fname); rv++; continue; } /* count the characters, etc. */ copyout(fp); /* now close it */ (void) fclose(fp); } putchar('\n'); /* * say goodbye! */ exit(rv); }