How to FSEEK previous line of text?

Lars Wirzenius wirzeniu at kruuna.Helsinki.FI
Thu May 9 08:54:47 AEST 1991


In article <4508.28269613 at iccgcc.decnet.ab.com> maslar at iccgcc.decnet.ab.com writes:
>Does anyone know of a function or technique that is similar to FSEEK
>that will allow me to go back to the previous line?

You can do two things: 1) save all the previous text in a buffer in the
memory, or 2) save the positions of the starts of the lines in memory.

The former method requires plenty of memory (at least as much as the
file size), so it's probably not a very good idea. The latter method
requires you to call ftell at the start of each line and store the value
in an array, something like:

	long line_starts[MAX_LINES];

	/* ... */
	lines_starts[line_no] = ftell(input_file);
	/* read the line */
	/* ... */

Note that you can't assume that the value returned by ftell is in any
way related to the number of characters on the line, so you can't just
do fseek(f, -linelen, SEEK_CUR), well, at least not portably.

You might have a problem if the input isn't coming from a file that is
seekable, e.g. pipes and terminals aren't. In this case you could save
the input in a temporary file, and fseek that instead.

You might want to look at the source of less, which implements these
kinds of things.
-- 
Lars Wirzenius  wirzenius at cc.helsinki.fi



More information about the Comp.lang.c mailing list