php - PHP如何停止写入和截断
问题描述
我正在尝试在 php 中实现一种原子获取和设置。这是我到目前为止得到的。
function atomic_get_and_set($filename, $oldData, $newData)
{
$size = filesize($filename) + 100000;
$fp = fopen($filename, "c+");
$failure = "0";
if (flock($fp, LOCK_EX)) {
$current_content = fread($fp, $size);
if($current_content == $oldData) {
rewind($fp);
fwrite($fp, $newData);
} else {
$failure = "1".$current_content;
}
flock($fp, LOCK_UN);
}
fclose($fp);
return $failure;
}
如果我们读取的不是预期的旧日期“0”,则我试图返回以“1”开头的文件内容,否则写入文件。
我必须使用 C+ 或 a+ 打开文件,以确保在打开文件时不会删除文件内容。但是,以下情况失败:
file_put_contents("test.txt", "hello world");
atomic_get_and_set("test.txt", "hello world", "hallo");
确实,文件的结果是“你好世界”而不仅仅是“你好”,因为我没有找到如何告诉他在fwrite
. 有谁知道该怎么做?
解决方案
推荐阅读
- generics - Making a generic From/Into shortcut for two-steps From
- python - Python中具有任意起始位置的哈密顿路径
- apache-kafka - 是否可以跨 kafka 集群修复参数 min.insync.replicas?
- google-cloud-platform - 谷歌播放服务上的无限加载屏幕
- c# - c# Double.MinValue 和 Double.MaxValue 之间的随机数
- javascript - Three.js从点列表中绘制椭圆
- mule - 如何从有效载荷中的字符串值中获取值,
- android - 使用 Tensorflowlite 的 Android 应用程序中的 ML 项目
- .net-core - IIS下如何为不同环境配置dotnet core web app
- python - Mac 上的 Python os.cpu_count() 返回错误的内核数