Need efficient way to read file in reverse

Roy Smith roy at alanine.phri.nyu.edu
Wed Sep 19 01:28:18 AEST 1990


	Is there a standard, portable, efficient way to read a file in
reverse?  I'm doing random seeks in a file and occassionally want to be able
to find the beginning of the line into the middle of which I just seeked.
Right now, I'm using a simple-minded revgetc() I wrote which is basically:

	fseek (fp, -2L, FSEEK_CURRENT);
	getc (fp);

but which turns out to loose big, since it looks like it does a read(2) for
every call to getc().  Life is made worse by the fact that occasionally I
have very long (over 1kbyte) lines.  My application is currently spending
about 98% of its CPU time in revgetc(), according to gprof.

	Obviously, the thing to do is write a buffered revgetc().  Modifying
the standard getc() macro to traverse the buffer in the opposite direction
would be easy, but the result would be non-portable.  To make it portable, I
want to write it using the stdio functions, and that's the hitch.  The
warning in the fseek/ftell man page about stdio read pointers possibly being
magic cookies makes it hard for me to calculate how far back to seek to read
in the preceeding, say, 1024 bytes.  What to do?
--
Roy Smith, Public Health Research Institute
455 First Avenue, New York, NY 10016
roy at alanine.phri.nyu.edu -OR- {att,cmcl2,rutgers,hombre}!phri!roy
"Arcane?  Did you say arcane?  It wouldn't be Unix if it wasn't arcane!"



More information about the Comp.unix.wizards mailing list