Today, when writing Unicode files with fwrite, there is a problem with the code as follows
_wfopen_s(&fp,L"out.txt",L"w+"); if (fp) { //写入unicode文件头 const char*utf16head"\xFF\xFE"; fwrite21,fp); //fwrite(line.c_str(), 2, line.size(),fp); fwrite(L"dsad\n"25,fp); fclose(fp); }
found "\ n" was written in 0x0d 0x0a 0x00 more than a 0x0d, resulting in text parsing errors, resulting in garbled characters. After checking that the file was opened in the way the problem. W is open file in text mode, WB is binary mode open file.
When you open a file as text, the Fwrite function joins 0x0d in front of it every time a 0x0a is encountered. This is because in order to be compatible with Linux, originally changed line originally is 0A (' \ n '), Microsoft changed \ r \ n, that is, from 0 A to 0D 0 a.
Summary, when you open in W mode, write to the file \ n, is actually the underlying API to help you write a \ r. So write to \ r \ n, such as fwrite (L "dsad\r\n", 2, 6,FP) is actually written to dsad\r\r\n.
While WB writes in binary, there is no action to add content. So change the open mode to "wb+" on OK. The code is as follows
_wfopen_s(&fp,L"out.txt",L"wb+"); if (fp) { //写入unicode文件头 const char*utf16head"\xFF\xFE"; fwrite21,fp); //fwrite(line.c_str(), 2, line.size(),fp); fwrite(L"dsad\n"25,fp); fclose(fp); }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Fwrite Write Unicode return encountered garbled