Textfile Delete Row
Posted: Wed May 27, 2009 6:45 pm
Im making like a guest book and each new entry i saved on a new row in a text file is there a way i can choose a specific row and delete it?
Thanks
Thanks
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
You are using any database.. like MySQL ?tylerrowsell wrote:Im making like a guest book and each new entry i saved on a new row in a text file is there a way i can choose a specific row and delete it?
Thanks
Code: Select all
<?php
$file = fopen('test.txt', 'r+');
$lineToDelete = 3;
$counter = 1;
while ($counter < $lineToDelete) {
fgets($file); // skip
$counter++;
}
$write = true;
$position = ftell($file);
while ($line = fgets($file)) {
$newLine = fgets($file);
if ($newLine == false) break;
fseek($file, $position, SEEK_SET);
fwrite($file, $newLine);
$position = ftell($file);
}
fclose($file);
echo 'Done';
?>
Code: Select all
<?php
$size = filesize('test.txt');
$file = fopen('test.txt', 'r+');
$lineToDelete = 3;
$counter = 1;
while ($counter < $lineToDelete) {
fgets($file); // skip
$counter++;
}
$position = ftell($file);
$lineToRemove = fgets($file);
$bufferSize = strlen($lineToRemove);
while ($newLine = fread($file, $bufferSize)) {
fseek($file, $position, SEEK_SET);
fwrite($file, $newLine);
$position = ftell($file);
fseek($file, $bufferSize, SEEK_CUR);
}
ftruncate($file, $size - $bufferSize);
echo 'Done';
fclose($file);
?>Darhazer wrote:Actually in the code above, in the second while fread() with fixed size of buffer should be used instead of fgets(). Later this week I will edit the post with the correct code, if anyone don't fix this before me
Edit:
This one works correctly, still I feel some refactoring needed:Code: Select all
<?php $size = filesize('test.txt'); $file = fopen('test.txt', 'r+'); $lineToDelete = 3; $counter = 1; while ($counter < $lineToDelete) { fgets($file); // skip $counter++; } $position = ftell($file); $lineToRemove = fgets($file); $bufferSize = strlen($lineToRemove); while ($newLine = fread($file, $bufferSize)) { fseek($file, $position, SEEK_SET); fwrite($file, $newLine); $position = ftell($file); fseek($file, $bufferSize, SEEK_CUR); } ftruncate($file, $size - $bufferSize); echo 'Done'; fclose($file); ?>