我想要计算文件中的字符(以各种字符集),并使用函数'mbtowc'来检测字符。我无法弄清楚为什么字符和结果值是不同的。这是我的例子:为什么mbtowc不按预期计数字符集?
char buf[BUFFER_SIZE + MB_LEN_MAX];
int fd = open ("chinese_test", O_RDONLY);
unsigned int bytes, chars;
int bytes_read;
bytes = chars = 0;
while((bytes_read = read(fd, buf, BUFFER_SIZE)) > 0) {
wchar_t wc_buf[BUFFER_SIZE], *wcp;
char *p;
int n = 0;
bytes += bytes_read;
p = buf;
wcp = wc_buf;
while((n = mbtowc(wcp, p, MB_LEN_MAX)) > 0) {
p += n;
wcp++;
chars++;
}
}
printf("chars: %d\tbytes: %d\n", chars, bytes);
我测试的功能与一些GB2312字符的文本,但字符和字节太多不同的值。
我的测试返回 - >字符:4638 |字节:17473 但'wc'linux命令返回:字符:16770 |字节:17473
为什么这个区别?我做错了什么?
现在我已经有了这段代码,但结果仍然存在差异。
char buf[BUFFER_SIZE * MB_LEN_MAX];
int fd = open ("test_chinese", O_RDONLY), filled = 0;
unsigned int bytes, chars;
int bytes_read;
bytes = chars = 0;
while((bytes_read = read(fd, buf, BUFFER_SIZE)) > 0) {
wchar_t wc_buf[BUFFER_SIZE], *wcp;
char *p;
int n = 0;
bytes += bytes_read;
p = buf;
wcp = wc_buf;
while(bytes_read > 0) {
n = mbtowc(NULL, p, MB_LEN_MAX);
if (n <= 0) {
p++;
bytes_read--;
continue;
}
p += n;
bytes_read -= n;
chars++;
}
}
printf("\n\nchars: %d\tbytes: %d\n", chars, bytes);
,你可能会得到不完整的多字节序列。在'while'循环后面加上一个检查来确定'n'是否为负。 – 2012-02-10 01:32:39
@JoachimPileborg,我知道这个问题。有可能是17473字节的文件和BUFFER_SIZE = 1024有这么多的错误吗? – Figus 2012-02-10 01:42:56
可能不是,但你应该检查这个。瑞士人答复中指出的最可能的罪魁祸首是。 – 2012-02-10 01:48:27