Deepanshu Goyal
Deepanshu Goyal

Reputation: 2813

Delete last line from text file PHP using ftruncate

I am trying to delete last line from my text file in PHP using ftruncate, but the problem is the length if line will keep varying most of the times. And I dont want to use file_put_contents, so that I write the file again because the file could be in Megabytes.

Please any suggestions ?

Upvotes: 0

Views: 1226

Answers (1)

WizKid
WizKid

Reputation: 4908

To get you an idea what I meant something like this:

$fp = fopen('file.txt', 'r+');
$pos = filesize('file.txt');
while ($pos > 0) {
    $pos = max($pos - 1024, 0);
    fseek($fp, $pos);
    $tmp = fread($fp, 1024);
    $tmppos = strrpos($tmp, "\n");
    if ($tmppos !== false) {
        ftruncate($fp, $pos + $tmppos);
        break;
    }
}

It will read the last 1024 bytes. Find the last newline in that buffer if it exists. If it exists truncate to that position. If is doesn't exists it reads the next 1024 bytes and check them. And so on.

Upvotes: 2

Related Questions