Page 1 of 1
I dont understand this little piece of code
Posted: Fri Aug 08, 2003 9:05 pm
by skateis2s
I dont understand this code....
I found this code and it post data at the top of a text file, works great, but I dont understand it...

Can someone please explain it?
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);
thanks

Posted: Fri Aug 08, 2003 9:41 pm
by qartis
Code: Select all
//Imports old data
$handle = fopen($filename, "r");
$old_content = fread($handle, filesize ($filename));
fclose($handle);
This part opens the file up, gets all the data, and closes the file.
Code: Select all
//Sets up new data
$final_content = $data.$old_content;
This part creates a new batch of data out of the new data + the old data, stuck (concatenated) together.
Code: Select all
//Writes new data
$handle2 = fopen($filename, "w");
$finalwrite = fwrite($handle2, $final_content);
fclose($handle2);
This part opens up the file again, writes the just-created data blurb (containing the new + old data) and then closes the file again.
Posted: Fri Aug 08, 2003 9:50 pm
by skateis2s
ok thankyou, i understand it better now

but why the extra step?
Posted: Sat Aug 09, 2003 12:19 pm
by idylvox
Why, though is that better than this?:
function write_beg($filename, $data)
{
//Imports old data
$handle = fopen($filename, "rw");
$old_content = fread($handle, filesize ($filename));
//Sets up new data
$final_content = $data.$old_content;
//Writes new data
$finalwrite = fwrite($handle, $final_content);
fclose($handle);
}
Re: but why the extra step?
Posted: Sat Aug 09, 2003 4:48 pm
by JAM
idylvox wrote:Why, though is that better than this?
<cut>
Better and better, depends from what point of view. To learn the very basics or to save a couple of lines of code?
Re: but why the extra step?
Posted: Sun Aug 10, 2003 6:53 pm
by idylvox
JAM wrote:idylvox wrote:Why, though is that better than this?
<cut>
Better and better, depends from what point of view. To learn the very basics or to save a couple of lines of code?
It saves a couple lines of code and doesn't open the same file twice. I was just curious if there was a reason the extra was needed in the script.
I suppose from the standpoint of learning filehandlers and the like...
Posted: Mon Aug 11, 2003 12:09 am
by JAM
doesn't open the same file twice
...is probably the better reason. Youre very right, but if it's a copy-'n-paste code and you have no idea what it really means, I think it's a legit usage. =)