tags:

views:

54

answers:

4

This is my code:

$zplHandle = fopen($target_file,'w');
fwrite($zplHandle, $zplBlock01);
fwrite($zplHandle, $zplBlock02);
fwrite($zplHandle, $zplBlock03);
fclose($zplHandle);

When will the file be saved? Is it immediately after writing to it or after closing it?

I am asking this because I have Printfil listening to files in a folder and prints any file that is newly created. If PHP commits a save immediately after fwrite, I may run into issues of Printfil not capturing the subsequent writes.

Thank you for the help.

+2  A: 

the file will be saved on fclose. if you want to put the content to the file before, use fflush().

oezi
+2  A: 

PHP may or may not write the content immediately. There is a caching layer in between. You can force it to write using fflush(), but you can't force it to wait unless you use only one fwrite().

Sjoerd
True; OTOH, it will definitely write the content (and release file locks) when you call fclose().
Piskvor
@Sjoerd, @Piskvor: When will the folder monitoring software recognise the newly created file? Will it be after a save or after the lock release? This is crucial because there are some 8000 blocks of text content to be written to the file and the monitoring program should not be triggered anywhere in between. Thanks for your inputs.
Nirmal
I don't know, ask the people of PrintFil.
Sjoerd
+1  A: 

I made a tiny piece of code to test it and it seems that after fwrite the new content will be detected immediately,not after fclose.

Here's my test on Linux.

#!/usr/bin/env php
<?php
$f = fopen("file.txt","a+");
for($i=0;$i<10;$i++)
{
    sleep(1);
    fwrite($f,"something\n");
    echo $i," write ...\n";
}
fclose($f);
echo "stop write";
?>

After running the PHP script ,I use tail -f file.txt to detect the new content.And It shows new contents the same time as php's output tag.

SpawnCxy
OK. At least that gives some idea on the possibility of a flush before the intended time. I shall work on things based on your test results. Thanks Spawn!
Nirmal
+1  A: 

Assuming your working in PHP 5.x, try file_put_contents() instead, as it wraps the open/write/close into one call. http://us3.php.net/manual/en/function.file-put-contents.php

tsgrasser
Thank you for the tip :)
Nirmal