tags:

views:

44

answers:

2

I'm using fgets to read in text from simple files such as txt files however I need the ability to jump back to previous lines. Is there anyway to do this using fgets? Or should I just store the text in some sort a array/structure?

+2  A: 

fseek or a combination of fgetpos and fsetpos would be appropriate. AFAIK, there is no "go to line X" function; you'll have to save some information about each line (e.g. its starting position) instead, using fseek or fsetpos to move around.

You
And there's `ftell()`, though it is equivalent for most purposes to `fseek(fp, 0L, SEEK_CUR)`.
Jonathan Leffler
+1  A: 

You may be able to solve your problems with fseek() and friends ( http://linux.die.net/man/3/fseek ).

However, mixing the "fseek" functions with text files (especially if you're reading and writing to the same stream) may cause problems due to the library translation of line breaks.

If you're not too tight on memory, I'd go with saving information from previous lines.

Better yet, if possible review your algorithm/data structure so that you don't need to go back.

pmg