c++獲取文件編碼格式

int GetFileEncoding(char* filename)
{
	ifstream fs;
	char buff[512];
	fs.open(filename, ios::binary);
	if (!fs)
	{
		sprintf_s(buff, 512, "%s: Cannot open it.", filename);
		receive_log(buff);
		exit(-1);
	}
	unsigned char ch = 0x00;
	int coding = 0;
	fs.read((char*)& ch, sizeof(ch)); // Read first byte, left 8 bits.
	coding = ch << 8;
	fs.read((char*)& ch, sizeof(ch)); // Read second byte.
	coding += ch;

	FILEENCODING fileencoding = FileType_ANSI;
	switch (coding)
	{
	case 0xFFFE:
		// Unicode
		fileencoding = FileType_UNICODE_LE;
		break;
	case 0xFEFF:
		// Unicode Big Endian
		fileencoding = FileType_UNICODE_BE;
		break;
	case 0xEFBB:
		// UTF-8 BOM
		fileencoding = FileType_UTF8;
		break;
	default:
		// ANSI
		fileencoding = FileType_ANSI;
		break;
	}
	fs.close();
	return fileencoding;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章