$fp = fopen("./log", "a+");
fwrite($fp,"helloworld");
rewind($fp);
var_dump( fread($fp, 10) );
fclose($fp);
When this code is executed, two helloworlds are written to the file. Why is this?
And how to understand this passage:
Update mode permits reading and writing the same file; fflush or a
file-positioning function must be called between a read and a write or
vice versa. If the mode includes b after the initial letter, as in
"rb" or "w b", that indicates a binary file. Filenames are limited to
FILENAME_MAX characters. At most FOPEN_MAX files may be open at once.
The
fopen
的第二个参数为模式, 有r
,w
,b
,a
等模式, 其中a
表示append
, 也就是附加的意思, 打开时不会清空文件(把EOF
指向0), 而是把文件指针指向文件末尾. 所以这个时候如果直接写的话不会覆盖原有的内容. 通过rewind
function points the file pointer to the starting point. Writing at this time will overwrite the original content. For example:There are two reasons: you are in append mode and have not cleared the last helloworld, so the last time and the current time are both there
fopen("./log", "a+"); This sentence means to open a readable and writable file in an appended manner. If the file exists, the original content will be retained, and the data will be appended to the end of the file.
At this time, the $fp file pointer points to the end of the file for operation
fwrite($fp, '12345');
At this time, if fread($fp, 10) is printed directly, it will be an empty string. This is because the $fp file pointer points to the end of the file. If the length is specified, reading and printing backwards will definitely be empty.
And if you add rewind($fp); to rewind the position of the file pointer, you will find that the $fp pointer points to the beginning of the file, and printing fread($fp, 10) will result.
But when you open your log, it is appended to the end of the file every time.