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

标签 php file-io

为了学校作业,我必须用 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/

相关文章:

java - 检查文件路径是否正确,而不检查文件是否存在

c++ - 用 C++ 读取文本文件

javascript - 来自 ajax 中的 JSON 响应的值返回为未定义

javascript - SAS 打印到文件

file - 如何同时读取和写入二进制文件?

python - 通过文件读/写与Python代码交互?

PHP 和 MySQL 工作台

php - 在 mysql 语句中使用 if 语句

javascript - 网址方案 : open windows application on request [Electron]

php - Opcache 导致 PHP fatal error : Class '\xa0L\xdaor\x7f' not found