Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/17/84; site hpda.UUCP Path: utzoo!watmath!clyde!burl!ulysses!mhuxr!mhuxn!ihnp4!qantel!hplabs!hpda!sdawkins From: sdawkins@hpda.UUCP (Scott Dawkins) Newsgroups: net.sources Subject: Printing a file backwards Message-ID: <1213@hpda.UUCP> Date: Thu, 3-Oct-85 17:11:46 EDT Article-I.D.: hpda.1213 Posted: Thu Oct 3 17:11:46 1985 Date-Received: Sun, 6-Oct-85 05:55:47 EDT Distribution: net Organization: Hewlett Packard Co. Cupertino, CA. Lines: 59 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 <<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> /* backwards - print a file with the lines in the reverse order. * Hewlett-Packard Cupertino October 3, 1985 * Scott Dawkins {ucbvax|hplabs}!hpda!sdawkins */ #include 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); } Brought to you by Super Global Mega Corp .com