Printing a file backwards

Scott Dawkins sdawkins at hpda.UUCP
Fri Oct 4 07:11:46 AEST 1985


This is a (very) short C program that will print out a file
with the lines in the reverse order.  It 'fgetc()'s its way through
the file to count the number of characters, then backs up, spiting
out lines as it goes.  It does an fseek() and two fgets() for each
character in the file, so it does lots of disk accesses, but it
is still O(n), and will work for any size file, at least any file
with fewer characters then the maximum long int on your machine.

scott dawkins
(I wonder if Hewlett-Packard owns this code?)
{hplabs|ucbvax}!hpda!sdawkins

<<<<<<<<<<<<<<<<<<<<<<<cut here>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

/*  backwards - print a file with the lines in the reverse order.
 *  Hewlett-Packard Cupertino  October 3, 1985
 *  Scott Dawkins {ucbvax|hplabs}!hpda!sdawkins
 */
#include <stdio.h>

main(argc, argv)
int argc;
char **argv;
{
	FILE *in_file;    /* input file */
	long int count;   /* number of characters in the file */
	int c;	   	  /* input character */
	char out_line[BUFSIZ], *position; /* building space for lines */

	if ((in_file = fopen(argv[1], "r")) == NULL){
		fprintf(stderr, "backwards:  can't open file %s\n", argv[1]);
		exit(1);
		}

	/* find out how many characters are in the file */
	for (count = 0; (c = fgetc(in_file)) != EOF; ++count)
		;
	--count;

	out_line[BUFSIZ-1] = '\0'; /* be a nice UNIX citizen */
	position = &(out_line[BUFSIZ-2]);

	/* read the characters in the file in backwards order, printing
	 * out lines as they are formed (backwards!).
	 */
	for ( ; count >= 0; --count){
		fseek(in_file, count, 0);
		c = fgetc(in_file);
		if (c == '\n'){
			printf("%s", position);
			position = &(out_line[BUFSIZ-2]);
			*position = c;
			}
		else
			*(--position) = c;
		}
	printf("%s", position);  /* catch the last (first?) line */
	fclose(in_file);
	}



More information about the Comp.sources.unix mailing list