【问题标题】:fgets() returns false even though file is not empty即使文件不为空,fgets() 也会返回 false
【发布时间】:2013-08-31 09:40:41
【问题描述】:

我有一个表单,我可以将给定的输入保存到一个文本文件中,
但我无法从保存的文件中读取:

while(!feof($fileNotizen)) {
$rawLine = fgets($fileNotizen);
if($rawLine==false) {
  echo "An error occured while reading the file"; 
}


$rawLine 似乎总是假的,即使我之前使用过这个函数来填充文本文件:

function addToTable($notizFile) {
 fwrite($notizFile, $_POST["vorname"]." ".$_POST["nachname"]."#");
 $date = date(DATE_RFC850);
 fwrite($notizFile, $date."#");
 fwrite($notizFile, $_POST["notiz"].PHP_EOL);   
}


在我提交表单并收到错误消息后,如果我检查文本文件,一切都在那里,所以该功能正常工作。

如果有价值,我用这个命令打开文件:

$fileNotizen = fopen("notizen.txt", "a+");

问题会不会是指针已经在文件末尾,因此返回 false?

【问题讨论】:

    标签: php file fgets


    【解决方案1】:
    $fileNotizen = fopen("notizen.txt", "a+");
    

    a+ 打开以进行读/写,但将文件指针放在末尾​​strong>。因此,您必须先将fseek() 放在开头或查看fopen() flags 并根据您的需要进行更明智的选择。

    使用fseek($fileNotizen, 0, SEEK_SET); 倒带文件。

    【讨论】:

    • 这似乎是我需要的,但是添加它并没有改变输出,我也尝试了rewind($fileNotizen) 没有结果。
    • @Big_Chair 使用fseek($fileNotizen, 0, SEEK_SET); 倒回文件。并确保文件实际上已打开if($fileNotizen)。并使用__DIR__ 使用绝对路径。
    • 看来我的问题一定是由其他原因引起的,因为这似乎也没有帮助。不过感谢您的帮助!
    • 可能还想将您的测试更改为 if($rawLine===false) 您可能会从文件中得到一个虚假值(空行)
    【解决方案2】:

    要读取/获取文件的内容,试试这个函数:

        function read_file($file_name) {
            if (is_readable($file_name)) {
                $handle = fopen($file_name, "r");
                while (!feof($handle)) {
                    $content .= fgets($handle); 
                }
                return !empty($content) ? $content : "Empty file..";
            } else {
                return "This file is not readable.";
            }
        }
    

    如果您想查看显示在单独行中的文件内容,请使用<pre></pre> 标记,如下所示:

    echo "<pre>" . read_file("notizen.txt") . "</pre>";
    

    如果您想在文件中写入/添加内容,请尝试以下功能:

        function write_file($file_name, $content) {
            if (file_exists($file_name) && is_writable($file_name)) {
                $handle = fopen($file_name, "a");
                fwrite($handle, $content . "\n");
                fclose($handle);
            }
        }        
    

    你可以这样使用它:

    $content = "{$_POST["vorname"]} {$_POST["nachname"]}#" . date(DATE_RFC850) . "#{$_POST["notiz"]}";
    write_file("notizen.txt", $content);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-04
      • 2017-05-26
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多