问题描述
我需要更改文件中的单个字符。
我宁愿不使用像这样的辅助文件(伪代码):
read(theFile)
change(theFile)
$ b $ p $ e $ e $ e $ e $ e $ e $ e $ e $
rename(theFile2,theFile)
由于这样,有些进程可以在实际擦除时需要该文件。
相反,我想操作自己的文件,因为这样,我指望服务器的操作系统负责处理对文件的访问。
您需要使用 flock
来锁定文件。基于的代码示例:
<?php
$ fp = fopen(file.txt,r +);
if(flock($ fp,LOCK_EX)){//获得排他锁
//进行更改
fflush($ fp); //在释放锁之前刷新输出
flock($ fp,LOCK_UN); //释放锁
} else {
echo无法获得锁!
}
fclose($ fp);
?>
I need to change a single character in a file.
I'd rather not use an auxiliary file like so (pseudo code):read(theFile)
change(theFile)
write(theFile2)
erase(theFile)
rename(theFile2,theFile)
Since in this way, Some process can require that file when it is actually erased.
Rather, I'd like to operate on that own file, because this way, I count on the server's os to take care of timing and process access to the file.
You'll want to use flock
to lock the file. Example based on code from the PHP docs:
<?php
$fp = fopen("file.txt", "r+");
if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
//make your changes
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't get the lock!";
}
fclose($fp);
?>
这篇关于改变一个文件的单个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!