检测文件编码格式
正文完全检测
检测文本文件的编码格式。
函数结束后文件内指针指向开始位置。
参数:文件指针。
返回值:
- 0:ANSI
- 1:UTF-8
- 2:带BOM的UTF-8
- 3:UTF-16 LE
- 4:UTF-16 BE
- 5:UTF-32 LE
- 6:UTF-32 BE
#include <stdio.h>
#include <stdlib.h>
int testEncoding(FILE* fp)
{
unsigned int bom;
int i;
if (fp == NULL)
return -1;
rewind(fp);
for (i = 0, bom = 0; i < 4; i++)
{
bom = bom << 8;
bom = bom + (unsigned char)fgetc(fp);
}
rewind(fp);
if (bom == 0x0000FEFF)
return 6;
else if (bom == 0xFFFE0000)
return 5;
else if (bom >= 0xFEFF0001 && bom <= 0xFEFFFFFF)
return 4;
else if (bom >= 0xFFFE0001 && bom <= 0xFFFEFFFF)
return 3;
else if (bom >= 0xEFBBBF00 && bom <= 0xEFBBBFFF)
return 2;
else//如果执行到此意味着文本没有BOM
{
unsigned char test;
int size = 0;
while (1)//进入正文检测
{
test = fgetc(fp);//从fp获取一个待检测字符test。
if (feof(fp) != 0)//如果fp指向文档结束位置,跳出循环。
break;
if (test >= 0xF0 && test < 0xF8)//test在1111 0000到1111 0111之间,这是一个4字节字符的首字节。
size = 4;
else if (test >= 0xE0 && test < 0xF0)//test在1110 0000到1110 1111之间,这是一个3字节字符的首字节。
size = 3;
else if (test >= 0xC0 && test < 0xE0)//test在1100 0000到1101 1111之间,这是一个2字节字符的首字节。
size = 2;
else if (test >= 0x80 && test < 0xC0)//test在1000 0000到1011 1111之间,这是一个中间字节。
size = 0;
else if (test >= 0x00 && test < 0x80)//test在0000 0000到0111 1111之间,这是一个1字节字符。
size = 1;
else//RFC 3629规定,5字节字符和6字节字符已经无法出现在合法 UTF-8序列中。
{
rewind(fp);
return 0;
}
if (size == 0 || size == 1)
continue;
else
{
for (i = 0; i < size - 1; i++)//检测多字节字符是否符合UTF-8结构。
{
test = fgetc(fp);
if (test < 0x80 || test >= 0xC0)
{
rewind(fp);
return 0;
}
}
}
}
}
rewind(fp);
return 1;
}