Re: Read only last line-



Joe Wright <joewwright@xxxxxxxxxxx> writes:
[...]
If it's a text file stream and all lines are terminated with '\n'
including the last one, we first trip through the file looking for
'\n' characters and recording the position (offset) of the next
character.

FILE *fp = fopen("file.txt", "r");
int ch;
long prev = 0, here;
while ((ch = fgetc(fp)) != EOF)
if (ch == '\n') {
prev = here;
here = ftell(fp);
}

At EOF, here is really the end of file and prev is the offset to the
previous (last) line.

fseek(fp, prev, SEEK_SET);

points you to it. Good luck.

That will work (assuming the file is seekable at all), but it requires
reading the entire file, which the OP was trying to avoid.

It records the position of the beginning of the last line, which will
let you re-read from that position, but it assumes that the file isn't
going to change; if you're assuming that, you might as well just read
the entire file and remember the last line.

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.



Relevant Pages

  • Re: !ALT.SUPPORT.CHRONIC-PAIN FAQ 2/2
    ... Tagline, 70 characters long, last seen in Nevada. ... Prev by Date: ...
    (alt.support.chronic-pain)
  • Re: Need Huntron HTR1005B-1S manual or App notes
    ... MasonDG44 at comcast dot net (Just substitute the appropriate characters in ... Never take a laxative and a sleeping pill at the same time!! ... Prev by Date: ...
    (sci.electronics.repair)
  • Re: X-ternals: What happened to them
    ... I read that handbook. ... I just don't get why the characters didn't seek ... an immediately resolution. ... Prev by Date: ...
    (rec.arts.comics.marvel.xbooks)
  • Re: Prokofiev"s 3rd Piano Concerto
    ... Grab the recording of it and start re-listening:) ... Prev by Date: ...
    (rec.music.classical.recordings)
  • Re: Document variables
    ... > testing and it looks like it fails if I try to make a string longer than ... > about 65000 characters. ... > large amount of text to a field? ... Prev by Date: ...
    (microsoft.public.word.vba.customization)