繁体   English   中英

fwrite如果文件不存在?

[英]fwrite if file doesn't exist?

如果它不存在,是否可以只用PHP编写文件?

$file = fopen("test.txt","w");
echo fwrite($file,"Some Code Here");
fclose($file);

因此,如果文件存在,代码将不会编写代码,但如果文件不存在,它将创建一个新文件并编写代码

提前致谢!

你可以使用fopen()模式为x而不是w ,如果文件已经存在,这将使fopen失败。 与使用file_exists相比,检查这样的优点是,如果在检查存在和实际打开文件之间创建文件,它将不会出现错误。 缺点是,如果文件已经存在,它(有点奇怪)会生成E_WARNING。

换句话说(在@ ThiefMaster下面的评论的帮助下),像是;

$file = @fopen("test.txt","x");
if($file)
{
    echo fwrite($file,"Some Code Here"); 
    fclose($file); 
}

在执行代码之前,如果文件存在,请检查file_exists($ filename)。

if (!file_exists("test.txt")) {
    $file = fopen("test.txt","w");
    echo fwrite($file,"Some Code Here");
    fclose($file); 
}

创建了一个名为$ file的变量。 此变量包含我们要创建的文件的名称。

使用PHP的is_file函数,我们检查文件是否已存在。

如果is_file返回一个布尔值FALSE值,那么我们的文件名就不存在了。

如果文件不存在,我们使用函数file_put_contents创建文件。

//The name of the file that we want to create if it doesn't exist.
$file = 'test.txt';

//Use the function is_file to check if the file already exists or not.
if(!is_file($file)){
    //Some simple example content.
    $contents = 'This is a test!';
    //Save our content to the file.
    file_put_contents($file, $contents);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM