c - fwprintf 省略宽字符

标签 c file mingw widechar

我正在尝试在 Windows 上使用 MinGW C 创建宽字 rune 件,但是宽字符似乎被省略了。我的代码:

const wchar_t* str = L"příšerně žluťoučký kůň úpěl ďábelské ódy";
FILE* fd = fopen("file.txt","w");
// FILE* fd = _wfopen(L"demo.txgs",L"w"); // attempt to open wide file doesn't help
fwide(fd,1); // attempt to force wide mode, doesn't help
fwprintf(fd,L"%ls",str);
// fputws(p,fd); // stops output after writing "p" (1B file size)
fclose(fd);

文件内容

píern luouký k úpl ábelské ódy

文件大小为30B,所以宽字符确实丢失了。如何说服编译器编写它们?

正如 @chqrlie 在评论中建议的那样:结果

fwrite(str, 1, sizeof(L"příšerně žluťoučký kůň úpěl ďábelské ódy"), fd);

是 82(我猜是 2*30 + 2*10(省略字符)+ 2(宽尾随零))。

引用 from here 也可能有用。

The external representation of wide characters in files are multibyte characters: These are obtained as if wcrtomb was called to convert each wide character (using the stream's internal mbstate_t object).

这解释了为什么 ISO-8859-1 字符在文件中是单字节,但我不知道如何使用此信息来解决我的问题。执行相反的任务(将多字节 UTF-8 读取为宽字符)我无法使用 mbtowc并最终使用 winAPI 的 MultiByteToWideChar .

最佳答案

我不是 Windows 用户,但您可以尝试以下操作:

const wchar_t *str = L"příšerně žluťoučký kůň úpěl ďábelské ódy";
FILE *fd = fopen("file.txt", "w,ccs=UTF-8");
fwprintf(fd, L"%ls", str);
fclose(fd);

我从这个问题中得到了这个想法:How do I write a UTF-8 encoded string to a file in windows, in C++

关于c - fwprintf 省略宽字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35928843/

相关文章:

c - 如何使用基于 OpenSSL 的客户端提取预主 key ?

c - 二进制检测或二进制代码中的图像和例程是什么?

c - 如何从堆栈中删除重复项?

c++ - : Expected constructor,析构函数错误,或者 '.' token之前的类型转换 - 理解fstream

windows - FFmpeg 编译与编码器 x264 未找到 Windows

c++ - 具体如何在 Qt Creator 中添加编译器?

python - Cython 静态链接与 python 运行时?

c - 如何在C中打印双指针值

ios - iOS 文件名中允许使用哪些字符?

c# - 在 C# 中规范文件路径