Re: Read only last line-
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Sun, 19 Feb 2006 16:20:03 GMT
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.
.
- Follow-Ups:
- Re: Read only last line-
- From: Joe Wright
- Re: Read only last line-
- References:
- Read only last line-
- From: RyanS09
- Re: Read only last line-
- From: Michael Mair
- Re: Read only last line-
- From: Eric Sosman
- Re: Read only last line-
- From: Joe Wright
- Read only last line-
- Prev by Date: Re: function pointer to itself
- Next by Date: Re: Plauger, size_t and ptrdiff_t
- Previous by thread: Re: Read only last line-
- Next by thread: Re: Read only last line-
- Index(es):
Relevant Pages
|