Forum Moderators: coopster

Message Too Old, No Replies

Appending to the top of a file

I think I'm doing something wrong with rewind()

         

milocold

12:55 am on Feb 28, 2009 (gmt 0)

10+ Year Member



Hi Fellas,

So I'm working on building a small error logging thingy and I want the error messages to append to the top of the error log.

Here's my testing code:

$str = 'foobar';

(file_exists('logs/Error_Logs.txt'))? $strMode = 'at': $strMode = 'wt';

$rFileHandle = fopen( '[path]/Error_Logs.txt', $strMode);
rewind($rFileHandle);

fwrite($rFileHandle, $str);
fclose($rFileHandle);

I can't get this to work at all, it just keeps appending at the end. Am I missing something with my modes? Tried using fseek($handle, 0, SEEK_SET) but that didn't work either.

I'm just super curious...I mean...crazy-slap-my-best-friend curious!

Thanks in advance,

M. Cold

franco190453

2:34 am on Feb 28, 2009 (gmt 0)

10+ Year Member



try this ->

$myfile = file('[path]/Error_logs.txt');
$count = count($myfile);
$rFileHandle = fopen('[path]/Error_logd.txt', 'w');
fwrite($rFileHandle, $str);
for($x = 0; $x < $#*$!; $x++) {
fwrite($rFileHandle, $myfile[$x]);
}
fclose........

Regards
Franco

milocold

8:59 am on Feb 28, 2009 (gmt 0)

10+ Year Member



Hi franco190453,

Thanks for the reply! So, I haven't tested your code yet, but are you suggesting that I read in everything already in the file, add my new log (replacing all content in the file) and slapping the old content to that?

If that's the case, I did think about doing that but I was worried about performance verses just resetting the file's pointer. My thinking was that if the log gets huge, reading it in prior to writing to it could be a serious ding in performance.

Thanks again dude,

M. Cold