'w' turns on writing mode, points the file pointer to the file header and truncates the file size to zero. If the file does not exist, try to create it.
'a' opens in writing mode and points the file pointer to the end of the file. If the file does not exist, try to create it.
It seems that these two writing methods are different, but how come the results of my test are the same?
code show as below:
<?php
$dir = "./a/";
$txt = '1.txt';
$fh = fopen($txt, 'w');
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
if ($file == '.' || $file == '..') {
continue;
}
fwrite($fh, $file."\n");
}
closedir($dh);
?>
Read the file in the a folder and write it into the text. How come the result is the same if fopen is w or a?
大家讲道理2017-05-24 11:32:31
You first write some content in 1.txt, and then you can see the difference by testing w and a
To put it simply, for a text file that already has content, w is to clear the existing content and then write it, and a is to append content based on the existing content
For a brand new text file, both are the same
大家讲道理2017-05-24 11:32:31
If 1.txt does not exist or the content is empty, then appending and rewriting have the same effect.
If 1.txt exists and has content, the effect is different.
某草草2017-05-24 11:32:31
a模式
是追加,这一句是重点,将文件指针指向文件末尾,如果原来文件存在,那么要写入的内容将添加到文件末尾,你那个例子,是创建新文件了,等同于w模式