gpt4 book ai didi

php - PHP 中的文件 IO 不起作用

转载 作者:行者123 更新时间:2023-12-03 23:02:17 25 4
gpt4 key购买 nike

为了学校作业,我必须用 PHP 编写脚本。它必须创建一个带有名称的数组并将该数组写入文件。然后它必须删除数组,读取文件中的名称并回显它们。

这行不通:

<?php
$names = array("Name 1", "Name 2", "Name 3", "Name 4", "Name 5");
$filename = "names.txt";
$handle = fopen($filename, "wb+"); //open as read and write
$string = implode("\r\n", $names); //name on each line
fwrite($handle, $string); //write line

$names = array(); //empty array
print_r($names); //print empty array
$string = fread($handle, filesize($filename)); //read file
$names = explode("\r\n", $string); //lines to array
foreach ($names as $name) {
echo("<br>\n$name");
}
fclose($handle);
?>

但这行得通:

<?php
$names = array("Name 1", "Name 2", "Name 3", "Name 4", "Name 5");
$filename = "names.txt";
$handle = fopen($filename, "wb"); //open as write
$string = implode("\r\n", $names); //name on each line
fwrite($handle, $string); //write line
fclose($handle); //close

$handle = fopen($filename, "r"); //open as read
$names = array(); //empty array
print_r($names); //print empty array
$string = fread($handle, filesize($filename)); //read file
$names = explode("\r\n", $string); //lines to array
foreach ($names as $name) {
echo("<br>\n$name");
}
fclose($handle);
?>

当我关闭并重新打开文件时,我不明白为什么它会起作用。任何帮助将不胜感激。

最佳答案

你所需要的只是重新启动文件指针,因为在使用 fwrite() 时:

fwrite() writes the contents of string to the file stream pointed to by handle.

  • length bytes have been read
  • EOF (end of file) is reached
  • a packet becomes available or the socket timeout occurs (for network streams)
  • if the stream is read buffered and it does not represent a plain file, at most one read of up to a number of bytes equal to the chunk size (usually 8192) is made; depending on the previously buffered data, the size of the returned data may be larger than the chunk size.

如果你看fread()

fread() reads up to length bytes from the file pointer referenced by handle. Reading stops as soon as one of the these conditions is met:

因此在您调用 fread($handle, filesize($filename)); 时您已经在文件末尾 因此不会显示任何内容.

要解决这个问题,只需使用 fseek 将指针重新指向文件的开头

示例:

 fseek($handle, 0);

你不需要关闭文件..你的第一个代码会完美地工作

编辑

你也可以rewind来自 PHP 文档

Sets the file position indicator for handle to the beginning of the file stream.

 rewind($handle);

关于php - PHP 中的文件 IO 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13705466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com