gpt4 book ai didi

创建使用 UTF-8 编码的文件

转载 作者:太空宇宙 更新时间:2023-11-04 08:18:00 35 4
gpt4 key购买 nike

我正在尝试创建一个文件并使用 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 中检查文件的编码,它会显示:

"windows-1252"

有没有更好的方法来检查文件的编码?

任何能为我指明正确方向的提示都非常好,感觉这应该不难做到。

最佳答案

您应该为convertedChar 分配内存并将c 设置为197,这是埃字符(Å) 的unicode char id。然后,您现在可以将此字符编码为 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);

关于创建使用 UTF-8 编码的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34739619/

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