#include <stdio.h>
#include <string.h>
// 判断一个字节是否为汉字的一部分
int is_gbk_char(unsigned char c) {
return (c & 0x80) && (c >= 0xA1 && c <= 0xF7);
}
// 读取GBK编码的汉字文件
void read_gbk_file(const char *filename) {
FILE *file = fopen(filename, "rb");
if (file == NULL) {
printf("无法打开文件: %s
", filename);
return;
}
unsigned char buffer[2];
while (fread(buffer, 1, 2, file) == 2) {
if (is_gbk_char(buffer[0]) && is_gbk_char(buffer[1])) {
// 如果两个字节都是汉字的一部分,将它们组合成一个汉字并输出
unsigned int code = (buffer[0] << 8) | buffer[1];
char ch = code;
printf("%c", ch);
} else {
// 如果两个字节不都是汉字的一部分,直接输出它们
for (int i = 0; i < 2; i++) {
printf("%02X", buffer[i]);
}
}
}
fclose(file);
}
int main() {
read_gbk_file("test.txt");
return 0;
}