Page 1 of 1

Write to Beginning of File

Posted: Mon Apr 10, 2006 7:29 pm
by Toot4fun
I have an error log where I'd like to write the latest entry to the top of the file rather than the bottom. Is this possible to do? If so, how is it done?

Thanks.

Posted: Mon Apr 10, 2006 7:47 pm
by Nathaniel
fopen your error log using mode 'r+', "Open for reading and writing; place the file pointer at the beginning of the file."

Posted: Mon Apr 10, 2006 11:04 pm
by feyd
Note that writing data immediately after opening the file in Nathaniel's method will overwrite data in the file already. This is likely not the wanted effect. The only way to effectively do this is loading the file data into a variable, prepending the information and write the entire file back again. Not fun, but that's the nature of linear files.

Posted: Tue Apr 11, 2006 6:48 am
by litebearer
A quick funtion to accomplish your task..

Code: Select all

function write_beg($filename, $data)
{
  //Imports old data
  $handle = fopen($filename, "r");
  $old_content = fread($handle, filesize ($filename));
  fclose($handle);

  //Sets up new data
  $final_content = $data.$old_content;

  //Writes new data
  $handle2 = fopen($filename, "w");
  $finalwrite = fwrite($handle2, $final_content);
  fclose($handle2);
}
Lite...

ps: you could also treat the data as an array and then use array_unshift() to add the new data to the beginning