file_get_contents,空文件不能正常运行PHP

mpg*_*pgn 5 php file fgets file-get-contents

我尝试使用PHP的file_get_contents,但它不起作用.

有我的代码:

$filename = "/opt/gemel/test.txt";


if($filecontent = file_get_contents($filename)){

    $nom = fgets(STDIN);

    file_put_contents($filename, $nom, FILE_APPEND);
}
else
    echo "fail";
Run Code Online (Sandbox Code Playgroud)

我的文件test.txt是空的.(0个八位字节).他存在,但他是空的.

当我写入内容时,我的代码完美无缺,但如果他是空的,我的代码回显"失败"

为什么呢,为什么他不能打开文件text.txt

rae*_*kid 15

该函数file_get_contents返回文件中的字符串.如果文件不包含任何数据,则file_get_contents返回空字符串.如果你想尝试,var_dump('' == false);你会得到true.因此,即使可以读取文件,文件的内容也会计算到false.

如果你要使用这一行,你的代码应该工作:

if($filecontent = file_get_contents($filename) !== false){
Run Code Online (Sandbox Code Playgroud)

编辑; 链接到比较运算符的文档.