本例中文本间用“,”作为分隔符,在UNICODE下,原本用空格作为分隔符,发现貌似行不通哦~
问题:
Unicode文本文件以0xff、0xfe两个字节开头,后面是Unicode文本内容。在创建文件的时候先向文件写入0xff、0xfe两个字节,然后再写入Unicode字符串即可;在读文件的时候,先读出前两字节,然后将后面数据直接读入Unicode字符串缓冲区。至于二进制文件,直接把要写的数据写入文件即可。
网上其他方法:
一.UNICODE下写ANSI编码的文本
//小例子
str=_T("你好");
char szANSIString[MAX_PATH];
WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,str,-1,szANSIString,sizeof(szANSIString),NULL,NULL);
file.Write(szANSIString,4);
二.
//写文件
CString strFileName=strCurProjFullPath+_T("\\")+_T("OilType.dat");
CFile file(strFileName,CFile::modeCreate|CFile::modeWrite|FILE_FLAG_NO_BUFFERING);
//指明存储为Unicode格式
const unsigned char LeadBytes[] = {0xff, 0xfe};//网上有说是BOM头,尚未查阅先关资料
file.Write(LeadBytes, sizeof(LeadBytes));
for (iRows=0;iRows<iUsefulRowsCount;iRows++)
{
for (iCols=0;iCols<iClosCount;iCols++)
{
pCurrentCell=m_pGridCtrl->GetCell(iRows,iCols);
strCurCellTxt=pCurrentCell->GetText();
file.Write(strCurCellTxt,wcslen(strCurCellTxt)*sizeof(wchar_t));
if ((iClosCount-iCols) != 1)
{
file.Write(_T(","),wcslen(_T(","))*sizeof(wchar_t));//用逗号作为分隔符
}
}
file.Write(_T("\r\n"),wcslen(_T("\r\n"))*sizeof(wchar_t));
}
file.Close();
MessageBox(_T("保存完毕!"),_T("保存"),MB_OK);
///读文件
// CStdioFile stdFile(strFileFullPath,CFile::modeRead);
CString fileLineTxt=_T("");
CString cellTxt=_T("");
// Open the file with the specified encoding
FILE *fStream;
errno_t e = _tfopen_s(&fStream,strFileFullPath, _T("rt,ccs=UNICODE"));
if (e != 0) return; // failed..CString sRead;
CStdioFile stdFile(fStream); // open the file from this stream
CString sRead;
int iRowID=-1;
while( stdFile.ReadString(fileLineTxt))//每次读取一行内容
{
CAtlString str(fileLineTxt);
CAtlString resToken;
iRowID++;
for (int iColID=0,iPos=0;iColID<m_uGridColumnsCount+1;iColID++)
{
/*CString::Tokenize()碰到连续多个分隔字符是作为一个处理的,AfxExtractSubString()中多个分隔符可区分处理。*/
resToken= str.Tokenize(_T(","),iPos);
ASSERT(iPos!=-1);
pCell=m_pGridCtrl->GetCell(iRowID,iColID);
pCell->SetText(resToken);
}
}
stdFile.Close();