【发布时间】:2020-07-23 02:40:58
【问题描述】:
在我的课堂上,我们遇到了这个问题。我不知道如何解决它。
“下面的程序计算文件中的字符数,假设文件被编码为 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 是如何工作的吗?似乎很容易识别开始字节并跳到下一个开始。
-
UTF-8 被设计成微不足道的。有一个所有连续字节(您要忽略的字节)共有的属性,并且只能在连续字节中找到。这是什么?