Home >Backend Development >PHP Tutorial >php I used fwrite() to write a file, why did the file content change completely?

php I used fwrite() to write a file, why did the file content change completely?

WBOY
WBOYOriginal
2016-08-29 08:50:541450browse

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?

Reply content:

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. . .

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn