可以自动读取文本文件的编码
typedef enum TextFileType
{
?? ?TextFileType_ANSI = 0,
?? ?TextFileType_UNICODE,
?? ?TextFileType_UTF8
}TEXTFILETYPE;
TEXTFILETYPE xPub_GetTextFileType(const CString& strFileName, CString& tFileName)
{
?? ?TEXTFILETYPE fileType = TextFileType_ANSI;
?? ?CFile cfile;
?? ?if (cfile.Open(strFileName, CFile::modeRead | CFile::shareDenyWrite))
?? ?{
?? ??? ?tFileName = cfile.GetFileName();
?? ??? ?char buf[3];
?? ??? ?cfile.Read(buf, 3);
?? ??? ?if ((unsigned char)buf[0] == 0xFF
?? ??? ??? ?&& (unsigned char)buf[1] == 0xFE)
?? ??? ?{
?? ??? ??? ?fileType = TextFileType_UNICODE;
?? ??? ?}
?? ??? ?else if ((unsigned char)buf[0] == 0xEF
?? ??? ??? ?&& (unsigned char)buf[1] == 0xBB
?? ??? ??? ?&& (unsigned char)buf[2] == 0xBF)
?? ??? ?{
?? ??? ??? ?fileType = TextFileType_UTF8;
?? ??? ?}
?? ??? ?cfile.Close();
?? ?}
?? ?return fileType;
}
//读取文件filepath / tFileName 到 变量 string ss里,成功返回1,失败返回0
BOOL xPub_ReadTextFile(CString filepath, CString& tFileName, string& ss)
{
ss.clear();
FILE* f = new FILE();
TEXTFILETYPE fileType = xPub_GetTextFileType(filepath, tFileName);
errno_t err = _wfopen_s(&f, filepath, L"rb");
if (err != 0)
return 0;
long length = 0;
fseek(f, 0, SEEK_END);
length = ftell(f);
fseek(f, 0, SEEK_SET);
if (length <= 0)
{
fclose(f);
return 0;
}
char* buf;
switch (fileType)
{
case TextFileType_ANSI:
break;
case TextFileType_UNICODE:
length -= 2;
fseek(f, 2, 0);
break;
case TextFileType_UTF8:
length -= 3;
fseek(f, 3, 0);
break;
default:
break;
}
buf = new char[length + 1];
buf[0] = 0;
int fl = fread(buf, length, 1, f);
if (fl != 1) {
fclose(f);
delete[] buf;
return 0;
}
fclose(f);
ss.append(buf, length);
delete(buf);
return 1;
}
自己的VxTerm所用的其中一个读取会话文件时用的模块。目前运行情况良好。