[英]How to solve this UTF-8 encoding C problem?
在我的 class 中,我们遇到了这个问题。 我不知道如何解决它。
“下面的程序计算文件中的字符数,假设文件被编码为 ASCII。修改程序,使其计算文件中编码为 UTF-8 的字符数”
#include <stdbool.h>
#include <stdio.h>
typedef unsigned char BYTE;
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: ./count INPUT\n");
return 1;
}
FILE *file = fopen(argv[1], "r");
if (!file)
{
printf("Could not open file.\n");
return 1;
}
int count = 0;
while (true)
{
BYTE b;
fread(&b, 1, 1, file);
if (feof(file))
{
break;
}
count++;
}
printf("Number of characters: %i\n", count);
}
谁能帮我解决这个问题?
UTF-8的设计使得这是微不足道的。 有一个所有连续字节(您要忽略的字节)共有的属性,并且只能在连续字节中找到。 它是什么?
First Last Number of
Code Code bytes in Byte 1 Byte 2 Byte 3 Byte 4
Point Point encoding
-------- -------- --------- -------- -------- -------- --------
U+000000 U+00007F 1 0xxxxxxx
U+000080 U+0007FF 2 110xxxxx 10xxxxxx
U+000800 U+00FFFF 3 1110xxxx 10xxxxxx 10xxxxxx
U+010000 U+10FFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.