Re: Read only last line-
- From: Joe Wright <joewwright@xxxxxxxxxxx>
- Date: Sun, 19 Feb 2006 13:06:04 -0500
Keith Thompson wrote:
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.
Good morning Keith. Thank you for reading. Regardless what the OP was trying to avoid, we must read the entire file. Agreed? Who or what might change the file while I am reading it? Reading the file character at a time simplifies things so I don't need to know how long a line is. We can know how long the last line is by subtracting prev from here, allocating space for it, backing up (fseek()) to prev and reading the line.
It's a beautiful bright Sunday afternoon in Arlington. Who'sit on the Left Coast?
--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
.
- Follow-Ups:
- Re: Read only last line-
- From: Eric Sosman
- 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
- Re: Read only last line-
- From: Keith Thompson
- Read only last line-
- Prev by Date: Re: Pointer to pointers of structs.
- Next by Date: new programmer
- Previous by thread: Re: Read only last line-
- Next by thread: Re: Read only last line-
- Index(es):
Relevant Pages
|
Loading