通过二进制读取文本文件的前三个字节来判断是否是UTF-8编码,以下是最终代码。
string filename = “c:\Default.asp”;
ifstream fin( filename.c_str(),ios::binary);
if( !fin )
{
cout << “打开文件” << filename << “出错” << endl;
//exit(-1);
}
else
{
byte bytes[3];
fin.read((char *)&bytes,sizeof bytes);
if(bytes[0] == 0xEF&& bytes[1] == 0xBB && bytes[2] == 0xBF)
{
cout <<”UTF8″<}else
{
cout <<”GB2312″<}
}
fin.close();