C 读取字库

#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;
}

  

posted @ 2024-07-18 11:26  飞雪飘鸿  阅读(1)  评论(0编辑  收藏  举报
https://damo.alibaba.com/ https://tianchi.aliyun.com/course?spm=5176.21206777.J_3941670930.5.87dc17c9BZNvLL