1

大家,早安。
我有点卡住了。有没有办法只在特定条件下打开文件并清空它?

我想要的是:
1. fopen( file ) -->flock --> 读取文件内容
2. 如果满足某些条件,替换文件内容
3. unlock 和 fclose
问题是:
fopen (file, w+)事先清空文件,所以我无法读取内容
fopen (file, r+)如果我想写入它不会清空文件

我已经尝试ftruncate($fn,0)与 结合使用r+,但是将“null”写入文件
一种解决方法是首先读取文件内容然后打开它。但我试图从阅读的那一刻起一直锁定文件,直到我完成。
有人有什么想法吗?

编辑:
问题似乎是fwrite. ftruncate清除文件,但fwrite添加一个“nul”。100 次通过后,数据前面有一百个 'nul'

$pt = "../path/file";  
$fn = lock_file($pt);  
$i = fread($fn,100);  
ftruncate($fn,0);  
fwrite($fn,"data");  
fflush($fn);  
flock($fn, LOCK_UN);  
fclose($fn);        

function lock_file($file){
$fn = fopen($file, "c+");  
$try=0;  
do{  
if($try>0){usleep(rand(1,10000));}
$try ++;
}
while(!flock($fn, LOCK_EX | LOCK_NB) and $try <= 300);
if($try>=300){return FALSE;}
return $fn;
}

fseek($fn, 0); 感谢解决!

4

3 回答 3

1

Have you considered 'c' or 'c+' modes instead of 'w'?

As PHP manual says:

'c' This may be useful if it's desired to get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).

UPD: As for the code posted above:

I have tried your code and saw nulls in beginning of the file. However, when I added

 fseek($fn, 0);

before

 ftruncate($fn, 0);

everything went fine (without fseek, 0's are being appended)

于 2012-09-20T08:34:07.800 回答
1
fopen($fn, "a+");//opens file for appending, does not erase contents
fseek($fn, 0);//moves pointer to first position in file

之后,如有必要,您可以调用ftruncate 。

于 2012-09-20T08:33:02.333 回答
0
fopen($fn, 'c+'); // open the files in read / write, doesn't truncate on opening
fread($fn);
ftruncate($fn, 0);
于 2012-09-20T08:34:38.570 回答