Page 1 of 1

Move the File Pointer to the Beginning of the Last Line

Posted: Wed Dec 07, 2005 10:15 am
by charlie12345
Jcart | Please use

Code: Select all

and

Code: Select all

tags where appropriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]


I am able to read in the last line of the text file, whose lines are of varying length, via:

Code: Select all

$linecontent = " ";
       $contents = file("hit_counter.txt");
       $linenumber = sizeof("hit_counter.txt")+1;
       $linecontent = $contents[$linenumber];
I then need to decide whether to re-write the last line with new data, or append a new line.

I assume I can append a new line with:

Code: Select all

$handle = fopen($file,"a");
but if I need to rewrite the last line, I don't know how far back to move the file pointer.
I assume I could use 'fseek ($file,-offset, SEEK_END )' but how far back do I move it?

Strlen returns the length of the string, but fseek wants an offset in bytes.

Thanks,
Charlie


Jcart | Please use

Code: Select all

and

Code: Select all

tags where appropriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]

Re: Move the File Pointer to the Beginning of the Last Line

Posted: Wed Dec 07, 2005 11:01 am
by onion2k
charlie12345 wrote:Strlen returns the length of the string, but fseek wants an offset in bytes.
That's not a problem. strlen() doesn't actually return the number of characters .. it returns the number of bytes. That's why it doesn't work for multibyte character strings.

Posted: Wed Dec 07, 2005 12:17 pm
by josh
seek to the EOF then in a loop seek one character backwards at a time till you find a line break