我正在尝试使用C创建一个文件并使用 UTF-8 格式对其内容进行编码。我已经尝试过几个东西并环顾四周但我似乎无法找到问题的解决方案
这是我目前正在尝试的代码( u8_wc_tout8 函数取自here):
int u8_wc_toutf8(char *dest, u_int32_t ch)
{
if (ch < 0x80) {
dest[0] = (char)ch;
return 1;
}
if (ch < 0x800) {
dest[0] = (ch>>6) | 0xC0;
dest[1] = (ch & 0x3F) | 0x80;
return 2;
}
if (ch < 0x10000) {
dest[0] = (ch>>12) | 0xE0;
dest[1] = ((ch>>6) & 0x3F) | 0x80;
dest[2] = (ch & 0x3F) | 0x80;
return 3;
}
if (ch < 0x110000) {
dest[0] = (ch>>18) | 0xF0;
dest[1] = ((ch>>12) & 0x3F) | 0x80;
dest[2] = ((ch>>6) & 0x3F) | 0x80;
dest[3] = (ch & 0x3F) | 0x80;
return 4;
}
return 0;
}
int main ()
{
printf(setlocale(LC_ALL, "")); //Prints C.UTF-8
FILE * fout;
fout=fopen("out.txt","w");
u_int32_t c = 'Å';
char convertedChar[6];
int cNum = u8_wc_toutf8(convertedChar, c);
printf(convertedChar); //Prints ?
fprintf(fout, convertedChar);
fclose(fout);
printf("\nFile has been created...\n");
return 0;
}
当我在Windows中从命令提示符运行它时,它会打印?
,当我打开创建的文件时,我会得到一些奇怪的字符。如果我在文件中检查Firefox中的编码,它会说:
&#34;窗口1252&#34;
有没有更好的方法来检查文件的编码?
任何向我指出正确方向的提示都会非常好,感觉这应该不会那么难。
答案 0 :(得分:2)
您应该为convertedChar
分配内存并将c
设置为197,这是angstrom字符(Å)的unicode字符。然后,您现在可以根据需要在utf-8或其他任何内容中对此字符进行编码:
int main ()
{
FILE * fout;
fout=fopen("out.txt","wb");
u_int32_t c = 197; // Or 0xC5
char convertedChar[4];
int cNum = u8_wc_toutf8(convertedChar, c);
fwrite(convertedChar, sizeof(char), cNum, fout);
fclose(fout);
printf("\nFile has been created...\n");
return 0;
}
例如,在您的语言环境使用UTF-8编码的情况下,您可以使用它来在控制台上打印字符:
wchar_t wc;
mbtowc(&wc, convertedChar, sizeof(wchar_t));
putwc(wc, stdout);