Fwrite Write Unicode return encountered garbled

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.