數碼相框(三)電子書(附一)判斷檔案編碼格式
阿新 • • 發佈:2018-12-16
/* 功能:實現檔案編碼格式的判斷 通過一個檔案的最前面三個位元組,可以判斷出該的編碼型別: ANSI: 無格式定義;(第一個位元組開始就是檔案內容) Unicode: 前兩個位元組為FFFE; Unicode big endian: 前兩位元組為FEFF; UTF-8: 前兩位元組為EFBB,第三位元組為BF */ |
#include <stdio.h> #include <stdlib.h> #include <string.h> // 讀取一個檔案的最前面n個位元組,並以十六進位制形式輸出每個位元組的值 void readNBytes(char *fileName, int n) { FILE *fp = fopen(fileName, "r"); unsigned char *buf = (unsigned char*)malloc(sizeof(unsigned char)*n); int i; if(fp == NULL) { printf("open file [%s] failed.\n", fileName); return; } fread(buf, sizeof(unsigned char), n, fp); fclose(fp); printf("%s:\t", fileName); for(i = 0; i < n; i++) { printf("%x\t", buf[i]); } printf("\n"); free(buf); } void main() { char fileName[][50] = {"ansi.txt", "unicode.txt", "ubigendian.txt", "utf8.txt"}; int i; for(i = 0; i < 4; i++) { // 每個檔案中的內容都是:你what123456 readNBytes(fileName[i], 3); } }
每個測試檔案中的內容都是:你what123456
執行結果為:
ansi.txt: c4 e3 77
unicode.txt: ff fe 60
ubigendian.txt: fe ff 4f
utf8.txt: ef bb bf