【问题标题】:PHP fread() other length argument than filesizePHP fread() 文件大小以外的其他长度参数
【发布时间】:2021-02-07 22:08:09
【问题描述】:

我试图让 PHP 读取一个文件到最后,它工作得非常好,除非文件为空。然后它抛出一个错误说:
 Uncaught ValueError: fread(): Argument #2 ($length) must be greater than 0`
`strlen()`does not work in this case.

是否有一些关于长度的论点,例如“读取所有内容,如果它是空的,则忽略它”?这是PHP:

$data_file_read = fopen("data.txt","r");
$alldata = fread($data_file_read,filesize("data.txt"));
fclose($data_file_read);

【问题讨论】:

  • 哈哈我有时也会遇到这个问题,我发现在创建文件时在文件中写一些东西可以解决这个问题,就像 0 或 null 或类似的东西会很好。我也很好奇在这种情况下该怎么做,当这不是一个可行的选择时:P
  • 出现此错误的确切代码是什么?你是如何计算得到 0 的 $length 的?你在什么模式下打开文件?您在阅读之前是否与feof 核对过? (请点击edit 并在问题中添加适当的详细信息。)
  • 完成了,谢谢!你有代码。

标签: php fread filesize


【解决方案1】:

将文件的长度放入一个变量中并检查你的长度

$filename = "data.txt";
//
// Check file exists first
//
if (file_exists($filename) === true) {
   //
   // Get file length and check if it is > 0
   //
   $dataLength = filesize($filename);

   if ($dataLength > 0) {
      //
      // Finally read the data
      //
      $data_file_read = fopen($filename, "r");
      $alldata = fread($data_file_read, $dataLength);
      fclose($data_file_read);
   }
}

【讨论】:

    猜你喜欢
    • 2017-11-01
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多