printfile1.c

/*
 * PRINTLINE1 -- Read a file name and print it on the standard output
 * 	each line prefixed by the line number
 * 	this version uses fgets and fputs (last prints line directly)
 *
 * 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
 *
 * 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 fgets
 *
 * 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(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;
		}
		/* copy the file, putting line numbers in front of each line */
		copyout(fp);
		/* now close it */
		(void) fclose(fp);
	}
	putchar('\n');
	/*
	 * say goodbye!
	 */
	exit(rv);
}


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: [email protected]
ECS 36A, Programming & Problem Solving
Version of April 2, 2024 at 12:13PM

You can get the raw source code here.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh