gpt4 book ai didi

c - 制作宽字 rune 件

转载 作者:太空宇宙 更新时间:2023-11-04 05:29:45 24 4
gpt4 key购买 nike

#ifndef UNICODE
#define UNICODE
#endif

#include <stdio.h>
int main()
{
FILE* oFile;
oFile = _wfopen(L"foo.txt",L"w");
//*
fwprintf(oFile,L"%s", L"ęłó☺☻♥♦•ń");
fclose(oFile);
return 0;
}

为什么这个程序创建一个 ASCII 文件而不是 UTF-16,尽管所有函数都是宽的?!

foo.txt 内容:

za[question mark]ó[two question marks...] g[...four...] ja[another two...] [five*?] [and the last one]

这是不可转换的。

fwprintf(oFile,L"%c%c%s",0xFE,0xFF,L"zażółć gęśłą jaźń ☺☻♥♦• ć");

现在,无论设置小字节序标记还是大字节序标记,它都显示中文标记。

最佳答案

假设您使用的是 MSVC,引用 _wfopen 的文档(大胆的矿山):

The fopen function opens the file that is specified by filename. _wfopen is a wide-character version of fopen; the arguments to _wfopen are wide-character strings. Otherwise, _wfopen and fopen behave identically. Just using _wfopen has no effect on the coded character set that is used in the file stream.

进一步阅读文档:

fopen supports Unicode file streams. To open a Unicode file, pass a ccs flag that specifies the desired encoding to fopen, as follows.

fopen(&fp, "newfile.txt", "rw, ccs= encoding ");

Allowed values of encoding are UNICODE, UTF-8, and UTF-16LE.

以下代码写入一个 UTF-8 编码的文件。我将此源文件保存为 UTF-16BE、UTF-16LE 和 UTF-8,MSVC 能够正确编译和运行。

#include <stdio.h>

int main()
{
FILE* oFile;
oFile = fopen("foo.txt","w, ccs=UTF-8");
fwprintf(oFile,L"%s", L"ęłó☺☻♥♦•ń");
fclose(oFile);
return 0;
}

请注意,在 Windows 命令行上显示此输出需要切换到 UTF-8 代码页:

C:\x>chcp
Active code page: 1252

C:\x>x

C:\x>type foo.txt
ęłó☺☻♥♦•ń
C:\Users\metolone\Desktop\x>chcp 65001
Active code page: 65001

C:\x>type foo.txt
ęłó☺☻♥♦•ń

关于c - 制作宽字 rune 件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10769023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com