我有一个要写入的文件
<timestamp>hashedcertificate
<timestamp>hashedcertificate
<timestamp>hashedcertificate
(等)
根据某个请求,我正在读取数组中的所有时间戳和数组中的所有哈希字符串。
$valid = fopen("./valid", "r+");
if (!$valid) {
log::Write("Could not open file. Exiting..", DEBUG);
exit(1);
}
$isLocked = flock($valid, LOCK_EX);
while (!$isLocked)
$isLocked = flock($valid, LOCK_EX);
while (!feof($valid)) {
$pos_begin = strpos($line, "<");
$pos_end = strpos($line, ">", $pos_begin);
$timestamp = substr($line, $pos_begin+1, $pos_end - $pos_begin - 1);
$timestamps[] = $timestamp;
$storedCert = substr($line, $pos_end + 1);
$storedCerts[] = $storedCert;
log::Write(sprintf("Read: %s with timestamp %s", $storedCert, $timestamp), DEBUG);
$line = fgets($valid);
}
检查它们后(如果时间戳太旧则删除),我想将剩余的有效哈希值写回到文件中。
ftruncate($valid, 0);
$counter = 0;
foreach ($timestamps as $timestamp) {
$toWrite = "<" . $timestamp . ">" . $storedCerts[$counter] . "\n";
log::Write(sprintf("Writing: \n%s", $toWrite), DEBUG);
fputs($valid, $toWrite);
$counter += 1;
}
flock($valid, LOCK_UN);
fclose($valid);
但是我的文件总是看起来像这样:(我认为在 ftruncate 之后,因为当我打开文件以附加时间戳+哈希值时,它不会出现奇怪的东西;仅当从文件读取 + 删除数组元素 + ftruncate + 写回文件内容来了) (请忽略第一个哈希值;我将其临时更改为 crc32 以使其更短):
^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^ @^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@< 1378903136>9f71fb266d96afa161c1e52e8b65031c08997bdb5f215f7d
<1378903666>b0e15296
<1378903671>6b4132b9
<1378903695>b0e15296
我做错了什么?
最佳答案
难道你不应该在截断后执行 rewind() 来将指针重新重置到文件的开头吗?
关于php - ftruncate() 没有清空我的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18742099/