...

View Full Version : add line of text to beginning of file



STDestiny
03-25-2004, 12:47 AM
How do you add a line of text to the beginning of a file? I'm able to put it at the end of the file, but i need the new line at the beginning.

-Andrew

duniyadnd
03-25-2004, 01:28 AM
$file = 'locationOfFile';

$array = file($file);

$str = "new text";




for ($i = 0; $i<count($array); $i++) {

$str .= $array[$i];

}

$fp = fopen($file, "w+");
fwrite($fp, $str);
fclose($fp);

Didn't test it... so something like that...

Serex
03-25-2004, 04:20 PM
you were possibly using a instead of w


$fp = fopen($file, "w+");

the w+ writed to the start of a file and if not available then it creates, whereas a+ points to the end of the file

firepages
03-25-2004, 05:16 PM
nooooooooo ;) w+ will delete the contents of the file if exists , else create a new file.

You can't actually write to the beginning of a file as such , you can open a file and fseek() to the beginning of the file , but you will be overwriting the existing data at that part of the file.

duniyadnd 's example is a typical workaround , read the file into memory , add your data and re-save.

STDestiny
03-25-2004, 11:18 PM
Thanks, that's what i figured. The reason I originally asked was because I was trying to code my own blog, but I went instead with WordPress, so it doesn't matter anymore. Thanks for the info tho, I'm sure I'll use it in the future.

-Andrew



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum