C/C++文本文件件编码格式

 

判断一文本文件编码格式。打开.txt文件,文件-〉另存为-〉编码-〉ASCII,Unicode,Unicode big endian,UTF-8

根据文件头判断文件可能是上面的几种编码格式

WineHxe测试的文件头

unsigned char uniTxt[] = {0xFF, 0xFE};	// Unicode file header
unsigned char endianTxt[] = {0xFE, 0xFF};	// Unicode big endian file header
unsigned char utf8Txt[] = {0xEF, 0xBB, 0xBF};	// UTF_8 file header



菜鸟求拍砖

bool TextEncode(const char *fPath)
{
	char srcBuff[1024];
	char header[2];
	unsigned char uniTxt[] = {0xFF, 0xFE};			// Unicode file header
	unsigned char endianTxt[] = {0xFE, 0xFF};		// Unicode big endian file header
	unsigned char utf8Txt[] = {0xEF, 0xBB, 0xBF};	// UTF_8 file header
	int len = 0;
	int ascii = 0;

	FILE *pFile;
	pFile = fopen(fPath, "rb");
	if (NULL == pFile)
	{
		return false;
	}
	
	//  ASCII range(0~127)
	while (1)
	{
		len = fread(srcBuff, 1, 1024, pFile);
		if (0 == len)
		{
			break;
		}
		for (int i=0; i<len; i++)
		{
			header[0] = srcBuff[0];
			header[1] = srcBuff[1];
			header[2] = srcBuff[2];

			if (srcBuff[i]<0 || srcBuff[i]>127)
			{		
				ascii++;
			}
			
		}
	}
	
	if (0 == ascii)		// ASCII file
	{
		printf("ASCII text\n");
	}
	else if ((2 == ascii) && (0 == memcmp(header, uniTxt, sizeof(uniTxt))))		// Unicode file
	{
		printf("Unicode text\n");
	}
	else if ((2 == ascii) && (0 == memcmp(header, endianTxt, sizeof(endianTxt))))	//  Unicode big endian file
	{
		printf("Unicode big endian text\n");
	}
	else if ((3 == ascii) && (0 == memcmp(header, utf8Txt, sizeof(utf8Txt))))		// UTF-8 file
	{
		printf("UTF-8 text\n");
	} 
	else
	{
		printf("	Unknow\n");
	}
	fclose(pFile);
	return true; 
}


 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值