Home > Article > Backend Development > php I used fwrite() to write a file, why did the file content change completely?
I used fwrite() to write a file. Why did the file content change completely?
The original content of file 2.txt was
<code>★★★★★★★★★★★★</code>
Then I executed the following script:
<code>$res = fopen( "R:/2.txt" ,"r+" ); fwrite( $res , "r" ); fclose( $res );</code>
The result 2.txt became:
<code>r铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩?</code>
What’s going on? How to correct it?
I used fwrite() to write a file. Why did the file content change completely?
The original content of file 2.txt was
<code>★★★★★★★★★★★★</code>
Then I executed the following script:
<code>$res = fopen( "R:/2.txt" ,"r+" ); fwrite( $res , "r" ); fclose( $res );</code>
The result 2.txt became:
<code>r铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩铩?</code>
What’s going on? How to correct it?
Because this pentagram occupies more than one byte per character, you wrote r to cover the first byte, causing all subsequent characters to be destroyed, because it happens that the remaining bytes of the first character and the second character Just one byte can be spelled out to form a valid encoding.
If you want to truncate the file, you should ftruncate after writing.
Want to add content?
http://php.net/manual/en/func...
When a is selected as the opening method of fopen, it is appended.
No need to change, yes, it’s just that the editor mistakenly recognized the encoding of the document. . .