Re: Read only last line-



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 ---
.



Relevant Pages

  • Re: FILE Writing Error
    ... >> for reading and writing,but i add some character at the end of ... Prev by Date: ...
    (comp.lang.c)
  • Re: Decoding strategy
    ... just reading normally. ... So, memory mapped view is sure too be usable for a while, so I ... file access at any offset, so tearing problem can be prevented. ... an offset that's not the start of a character, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Output/Input Problem
    ... which i am not as i am reading only a character from ... Prev by Date: ...
    (comp.lang.c)
  • FILE Writing Error
    ... for reading and writing,but i add some character at the end of ... Prev by Date: ...
    (comp.lang.c)
  • Re: How do I read contents of a ZipEntry from a zip file?
    ... I did try that, and while it lets me do things like getEntry, that ... The methods for reading want to read an entire file ... want an offset at which to start reading, which I don't know how to ... Prev by Date: ...
    (comp.lang.java.programmer)

Loading