Forum Moderators: coopster
Right now I'm stuck at trying to open the file and write a line at the very beginning. Here's my code:
$f="myfile.txt";
fwrite(fopen($f,"a"),"Add This Line\n");
I know I'm opening this file in append mode, where it will always write my text at the end of the document, but I can't figure out any other mode that would allow me to open an existing document and not delete everything that is already in it.
And as far as removing the last line, I have no clue.
Any tips or advice would be much appreciated, thanks.
You need to read the contents of the file, assign the data to a new string, clear the original and then write the new file.
$string = '';
$file = file('myfile.txt');for ($i=0; $i<count($file); $i++)
{if ($i!=count($file)-1)
{
$string .= $file[$i];
}}
$start = 'First Line';
if (file_exists('myfile.txt'))
{
unlink('myfile.txt');
}$fp = fopen('myfile.txt', 'ab');
if ($fp)
{
fwrite($fp,$start."\n".trim($string));
fclose($fp);
}
Not tested, but something like that should work ok.
dc
[edit] Cheers Andrew. Worth noting that the file_put_contents function will only work in PHP5.
I was thinking there would be a direct way of adding and removing lines, but knowing this isn't possible is something great to know in the future.
Both your approaches to reading the file and rewriting a modified version worked great, thanks.
I do have two questions:
Is reading and writing files server intensive or scalable?
Also, what would happen if two read/write requests happened at the same time or overlapped? Would this corrupt the file or cause outstanding issues?
Thanks
Is reading and writing files server intensive or scalable?
Also, what would happen if two read/write requests happened at the same time or overlapped? Would this corrupt the file or cause outstanding issues?
If you need to add at the front of a file, consider other options, such as sorting while viewing, or even storing in different data structure (database comes to mind, but there are other solutions then just grabbing a SQL database as well).