Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!usc!snorkelwacker.mit.edu!bloom-beacon!eru!hagbard!sunic!news.funet.fi!hydra!klaava!kruuna!wirzeniu From: wirzeniu@kruuna.Helsinki.FI (Lars Wirzenius) Newsgroups: comp.lang.c Subject: Re: How to FSEEK previous line of text? Summary: Try saving ftell values in an array Message-ID: <1991May8.225447.10218@klaava.Helsinki.FI> Date: 8 May 91 22:54:47 GMT References: <4508.28269613@iccgcc.decnet.ab.com> Sender: news@klaava.Helsinki.FI (Uutis Ankka) Organization: University of Helsinki Lines: 31 In article <4508.28269613@iccgcc.decnet.ab.com> maslar@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@cc.helsinki.fi