Difference between fopen w and a
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-05-24 11:30:31
0
4
1013

'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?

曾经蜡笔没有小新
曾经蜡笔没有小新

reply all(4)
大家讲道理

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

大家讲道理

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.

给我你的怀抱

a is appended, not overwritten.
w is direct coverage.

某草草

a模式是追加,这一句是重点,将文件指针指向文件末尾,如果原来文件存在,那么要写入的内容将添加到文件末尾,你那个例子,是创建新文件了,等同于w模式

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!