Always write to begining of file
I am trying to have a page always write to the begining of a file, like append but to the start of it instead of from the end.
this next piece of code appends to the end of the file:
as you can see I already tried the rewind() but didnt succeed, and also failed when tried the fseek() so Im running out of ideas...
$fh = fopen($LogFile, 'a') or die("can't open file");
$Mensaje = "<b>".$_GET["Nick"]."</b> at ".date('d\/m\/Y H:i')." wrote:\"".$_POST["Mensaje"]."\"<br>";
It is a flat file and it is writing to it, just not where I want it...
Checking PHP Manual for fopen(), an 'a' mode opens a file for writing only and places the file pointer at the end of the file. Try using fopen()'s other mode like 'w' or 'r+' which places the file pointer at the beginning of the file.
// Just my two cents.
Last edited by che_rish; 01-25-2006 at 02:40 AM.
You can only either append to the end of a file, or overwrite the entire file; you cannot prepend to it. Basically you need to read in the entire contents of the file (such as with file_get_contents()), then open the file in "w" mode, output the new data, then output the file contents you previously read into memory.
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
ohh, its a shame.
Anyways its not hard to accomplish but I thought perhaps there was a function that already did this.
A simple solution would be to..
open a temp file and write in the data you want to pre append
open the file you want pre appended and then append the data that is in the old file,
delete the old file,
rename the temp file to the name of the old file you deleted...
hey presto! preappending simplified.
If you use a database, you make things even easier as you only need to run a routine to extract in the order you want.
And you can overwrite specific locations within the file without overwriting the whole file.
Originally Posted by NogDog
$fp = fopen('test.text','w+');
$content = 'My cat\'s name is spot';
$fp = fopen('test.text','r+');
echo file_get_contents('test.text'); // My dog's name is Spot
Last edited by bokeh; 01-25-2006 at 09:12 PM.
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)