2011-11-17 63 views
7

我有下面的代码,但我试图缩短它几乎是一两行,因为我敢肯定我的如果不需要评估,反正有下面的代码可以缩短到甚至是单数行吗?是否有可能做“如果文件存在然后追加,否则创建新文件”比这更短

if(file_exists($myFile)) 
    { 
     $fh = fopen($myFile, 'a'); 
     fwrite($fh, $message."\n"); 
    } 
    else 
    { 
     $fh = fopen($myFile, 'w'); 
     fwrite($fh, $message."\n"); 
    } 
+0

缩短它的原因是什么? – Marcus

+3

[fopen的PHP手册](http://php.net/fopen)明确指出'a':*“只打开以便写入;将文件指针放在文件末尾如果文件没有存在,试图创造它。“* - 那是什么问题? – Gordon

回答

41
if (file_exists($myFile)) { 
    $fh = fopen($myFile, 'a'); 
    fwrite($fh, $message."\n"); 
} else { 
    $fh = fopen($myFile, 'w'); 
    fwrite($fh, $message."\n"); 
} 
fclose($fh); 

==

if (file_exists($myFile)) { 
    $fh = fopen($myFile, 'a'); 
} else { 
    $fh = fopen($myFile, 'w'); 
} 
fwrite($fh, $message."\n"); 
fclose($fh); 

==

$fh = fopen($myFile, (file_exists($myFile)) ? 'a' : 'w'); 
fwrite($fh, $message."\n"); 
fclose($fh); 

==(因为a检查文件是否存在,如果不创建它)

$fh = fopen($myFile, 'a'); 
fwrite($fh, $message."\n"); 
fclose($fh); 

==

file_put_contents($myFile, $message."\n", FILE_APPEND); 

...当然,file_put_contents()是只有更好,如果它是你在给定的手柄执行只写。如果您在同一文件句柄上有任何后续致电fwrite()的呼叫,最好使用@ Pekka的答案。

4
$method = (file_exists($myFile)) ? 'a' : 'w'; 
$fh = fopen($myFile,$method); 
fwrite($fh, $message."\n"); 
2
$fh = file_exists($myFile) ? fopen($myFile, 'a') : fopen($myFile, 'w'); 
fwrite($fh, $message."\n"); 
+0

但是为什么?首先检查有什么意义? –

+0

你的回复更有意义:) – matino

16

嗯......为什么呢? a已经做到了你需要的所有东西。

仅供写作;将文件指针放在文件的末尾。如果文件不存在,请尝试创建它。

+0

+1我在想同样的事但不记得国旗 – Sarfraz

1

追加模式已经做了你所描述的。从PHP手册页获取fopen

'a':仅供打印,将文件指针放在文件的末尾。如果文件不存在,请尝试创建它。

2
$fh = (file_exists($myFile)) ? fopen($myFile,'a') : fopen($myFile,'w'); 
fwrite($fh, $message."\n"); 
0

相信a(追加)模式确实已经...追加如果不存在,否则创建新

fopen($myFile, "a"); 
0
$method = (file_exists($myFile)) ? 'a' : 'w'; 

$fh = fopen($myFile,$method); 

fwrite($fh, $message."\n"); 

是不是$ MYFILE包含绝对/相对路径..?

相关问题