There's a Un*x utility for automagically doing this, but it leaves the new
file blank, almost for sure...
man logrotate

Can we safely assume no *other* PHP script is going to be trying to write to
this chat file while you're messing with it?  If not, you really need to
move to a database solution...

I guess you could try to http://php.net/flock your file everywhere before
you open it for writing, but that sure won't scale up well!

Depending on whether or not you can get all the lines you want to keep in
RAM or not, you could either:
--------- not so large, last 1/4th fits in RAM ----
$filename = "./chat/chat.txt";
$file = fopen($filename, 'r') or die("Could not open $filename.");
$text = fseek($file, filesize($filename)*0.75);
$partial_line = fgets($file, 10000000);
$recent = fread($file, filesize($filename));
fclose($file);
$file = fopen($filename, 'w') or die("Could not open $filename");
fwrite($file, $recent);
fclose($file);
----------------------------------------------------

If the file might be too big for this, you'll need to read a piece at a time
and write it out to some other file, and then use http://php.net/copy

--
WARNING [EMAIL PROTECTED] address is an endangered species -- Use
[EMAIL PROTECTED]
Wanna help me out?  Like Music?  Buy a CD: http://l-i-e.com/artists.htm
Volunteer a little time: http://chatmusic.com/volunteer.htm
----- Original Message -----
From: Gerard Samuel <[EMAIL PROTECTED]>
Newsgroups: php.general
To: PHP <[EMAIL PROTECTED]>
Sent: Saturday, September 08, 2001 12:11 AM
Subject: files


> hey, I have a large file and I want to keep the last x row of it.  I
> figured out how to navigate to the point where I want to extract the
> data, but I cant figure out how to extact from the file current $fp and
> write out the data to another file.
> Think of it like this, when the file gets to be x bytes, get the last 20
> lines from it and copy it to another file, so that I could dump the old
> and replace it witht the new....
> Thanks.
>
>
> <--snip of example code-->
> $fp = fopen("./chat/chat.txt", "r+");
> $size = filesize("chat/chat.txt");
> $count = 0;
> while (!@feof($fp)) {
>          $lines = fgets($fp, 4096);
>          $count = $count + 1;
> }
> $count--; // return the correct # of lines in file
> echo "Lines: $count<br>";
> $offset = round($count - ($count / 4));
> echo "Offset: $offset<br>";
>
> $count = 0;
> rewind($fp);
> while ($count < $offset) {
>          $lines = fgets($fp, 4096);
>          $count = $count + 1;
> }
> echo "New Offset: $count<br>";
> $file = fread($fp);
> if (!copy($file, $file.'.bak')) {
>      print ("failed to copy $file...<br>\n");
> }
>
> fclose($fp);
>


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]

Reply via email to