【发布时间】:2012-04-20 12:41:40
【问题描述】:
我正在使用我在这里找到的代码,效果很好,但是当我尝试访问子目录中的文件时,它就是不想工作。
它获取一个文件,创建一个要写入的临时文件,然后在文件中查找一些文本并用新文本替换该文本,然后保存更新的文件,然后删除临时文件。
以下工作正常:
$reading = fopen('links.htm', 'r');
$writing = fopen('links.tmp', 'w+');
$replaced = false;
while (!feof($reading)) {
$line = fgets($reading);
if (stristr($line,'::template::')) {
$line = "replacement line!\n";
$replaced = true;
}
fputs($writing, $line);
}
fclose($reading); fclose($writing);
// might as well not overwrite the file if we didn't replace anything
if ($replaced)
{
rename('links.tmp', 'links.htm');
} else {
unlink('links.tmp');
}
这不起作用:
$reading = fopen('path/to/links.htm', 'r');
$writing = fopen('path/to/links.tmp', 'w+');
$replaced = false;
while (!feof($reading)) {
$line = fgets($reading);
if (stristr($line,'::template::')) {
$line = "replacement line!\n";
$replaced = true;
}
fputs($writing, $line);
}
fclose($reading); fclose($writing);
// might as well not overwrite the file if we didn't replace anything
if ($replaced)
{
rename('path/to/links.tmp', 'path/to/links.htm');
} else {
unlink('path/to/links.tmp');
}
有什么建议吗?
path 是绝对的,我之前在代码中定义了它,并使用它来创建文件和写入文件,但是当我希望上面的代码以同样的方式工作时,它只是不想这样做。
此外,文件夹权限已设置为写入和读取,这也可以正常工作。
在子文件夹中运行代码并且工作正常,但不是从顶级目录。
错误报告已关闭,现在开启:
该进程无法访问该文件,因为它正被另一个进程使用。 (代码:32)
【问题讨论】:
-
如果您在文件夹“path/to”上尝试 opendir (php.net/manual/en/function.opendir.php) 是否有效?也许您没有所需的访问权限。
-
是的,它可能只是一个错误的路径问题
-
它可以很好地读取路径并很好地显示路径中的所有文件。所以那行不通。
-
“不起作用”不是错误消息。发生什么了?你有错误吗?是否启用错误报告?你检查权限了吗?
-
表示目录已启用写入。并且正在向它写入文件,除了我所说的上面的代码在它必须写入子目录时不起作用。我在它必须写入的目录中对其进行了测试,它也运行良好。
标签: php replace file-handling