C語言判斷檔案編碼格式

來源:互聯網
上載者:User
/*功能:實現檔案編碼格式的判斷通過一個檔案的最前面三個位元組,可以判斷出該的編碼類別型: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++){// 每個檔案中的內容都是:你what123456readNBytes(fileName[i], 3);}}

每個測試檔案中的內容都是:你what123456

運行結果為:

ansi.txt:       c4      e3      77
unicode.txt:    ff      fe      60
ubigendian.txt: fe      ff      4f
utf8.txt:       ef      bb      bf

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.