[英]Creating file that uses UTF-8 encoding
我正在尝试创建一个文件,并使用C将其内容编码为UTF-8格式。我尝试了几件事,环顾四周,但似乎找不到解决该问题的方法。
这是我当前正在尝试的代码( u8_wc_tout8函数从此处获取 ):
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,这是埃字符(A)的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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.