Move the File Pointer to the Beginning of the Last Line

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
charlie12345
Forum Newbie
Posts: 14
Joined: Wed Nov 09, 2005 5:35 am

Move the File Pointer to the Beginning of the Last Line

Post 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]
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

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

Post 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.
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post by josh »

seek to the EOF then in a loop seek one character backwards at a time till you find a line break
Post Reply