//读取失败
#define READ_FAIL 0
//读取分隔符
#define READ_SEPARATOR 1
//读到行尾
#define READ_LINEEND 2
//是否是Unicode文件
BOOL WINAPI IsUnicodeFile(CFile &File);
//文件读取
int WINAPI ReadTxtFile(CFile &File, TCHAR chSeparator, CString &csRead, BOOL bUnicodeFlag);
//移到行尾
void WINAPI MoveLineEnd(CFile &File, BOOL bUnicodeFlag);
//写Unicode标记
void WINAPI WriteFileUnicodeFlag(CFile &File);
int ReadTextFileA(CFile &File, char chSeparator, CString &csRead)
{
int nRet = READ_FAIL;
char szReadA[MAX_PATH+1] = {0};
char chReadA;
int nReadCount = 0;
for (;;)
{
if (File.Read(&chReadA, sizeof(char)) == sizeof(char))
{
if (chReadA == chSeparator)
{
nRet = READ_SEPARATOR;
break;
}
else if (chReadA == '\r')
{
File.Read(&chReadA, sizeof(char));
if (chReadA == '\n')
{
nRet = READ_LINEEND;
break;
}
}
else
{
if (nReadCount >= MAX_PATH)
{
CString csReadPart(szReadA);
csRead += csReadPart;
memset(szReadA, 0x00, sizeof(szReadA));
nReadCount = 0;
}
szReadA[nReadCount] = chReadA;
nReadCount++;
}
}
else
break;
}
if (nReadCount > 0)
{
CString cs(szReadA);
csRead += cs;
}
return nRet;
}
int ReadTextFileW(CFile &File, TCHAR chSeparator, CString &csRead)
{
int nRet = READ_FAIL;
TCHAR szRead[MAX_PATH+1] = {0};
TCHAR chRead;
int nReadCount = 0;
for (;;)
{
if (File.Read(&chRead, sizeof(TCHAR)) == sizeof(TCHAR))
{
if (chRead == chSeparator)
{
nRet = READ_SEPARATOR;
break;
}
else if (chRead == _T('\r'))
{
File.Read(&chRead, sizeof(TCHAR));
if (chRead == _T('\n'))
{
nRet = READ_LINEEND;
break;
}
}
else
{
if (nReadCount >= MAX_PATH)
{
csRead += szRead;
memset(szRead, 0x00, sizeof(szRead));
nReadCount = 0;
}
szRead[nReadCount] = chRead;
nReadCount++;
}
}
else
break;
}
if (nReadCount > 0)
csRead += szRead;
return nRet;
}
void MoveLineEndA(CFile &File)
{
char chChar;
for (;;)
{
if (File.Read(&chChar, sizeof(char)) == sizeof(char))
{
if (chChar == '\r')
{
File.Read(&chChar, sizeof(char));
if (chChar == '\n')
break;
}
}
}
}
void MoveLineEndW(CFile &File)
{
TCHAR chChar;
for (;;)
{
if (File.Read(&chChar, sizeof(TCHAR)) == sizeof(TCHAR))
{
if (chChar == _T('\r'))
{
File.Read(&chChar, sizeof(TCHAR));
if (chChar == _T('\n'))
break;
}
}
}
}
BOOL WINAPI IsUnicodeFile(CFile &File)
{
BOOL bUnicode = FALSE;
WORD wUnicodeFlag = 0;
if (File.Read(&wUnicodeFlag, sizeof(WORD)) ==sizeof(WORD))
{
if ((wUnicodeFlag == 0xFFFE) || (wUnicodeFlag == 0xFEFF))
bUnicode = TRUE;
else
File.SeekToBegin();
}
return bUnicode;
}
int WINAPI ReadTxtFile(CFile &File, TCHAR chSeparator, CString &csRead, BOOL bUnicodeFlag)
{
int nRet = READ_FAIL;
csRead.Empty();
if (bUnicodeFlag)
{
nRet = ReadTextFileW(File, chSeparator, csRead);
}
else
{
//转换一下分隔符
CStringA csSeparatorA(chSeparator);
nRet = ReadTextFileA(File, csSeparatorA.GetAt(0), csRead);
}
csRead.TrimLeft();
csRead.TrimRight();
return nRet;
}
void WINAPI MoveLineEnd(CFile &File, BOOL bUnicodeFlag)
{
if (bUnicodeFlag)
MoveLineEndW(File);
else
MoveLineEndA(File);
}
void WINAPI WriteFileUnicodeFlag(CFile &File)
{
WORD wUnicodeFlag = 0xFEFF;
File.Write(&wUnicodeFlag, sizeof(WORD));
}