概述
一:写文档
1 创建文档并写入内容
CString filePath=L"C:\unicode.txt";
CStdioFile wfile;
if (!wfile.Open(filePath,CFile::modeCreate|CFile::modeWrite|CFile::typeBinary))
{
AfxMessageBox(L"文件无法修改");
return;
}
WORD sign=0xfeff; // unicode文档 标志
wfile.Write(&sign,2);
CString fileContent;
fileContent=L"UNICODE文档";
wfile.Write(fileContent.GetBuffer(),fileContent.GetLength()*2);
fileContent.ReleaseBuffer();
wfile.Close();
WORD sign=0xfeff;
wFile.Write(&sign,2);
//遍历list容器 写入文件
list<CString>::iterator it=fileList.begin();
for (it=fileList.begin();it!=fileList.end();it++)
{
str=*it;
//写入CString类型的字符串
wFile.Write(str.GetBuffer(),str.GetLength()*2);
str.ReleaseBuffer();
//使用WriteString 写入回车换行符
wFile.WriteString(L"rn");
}
wFile.Close();
2 判断文档是否存在,若存在,则在文档末尾添加内容,若不存在,重新创建
CString filePath=L"c:\test.txt";
CStdioFile wfile;
CFileFind fileFind;
if(!fileFind.FindFile(filePath) // 查找文件是否存在
{
if (!wfile.Open(filePath,CFile::modeWrite|CFile::modeCreate|CFile::typeBinary)) //unicode 必须以二进制打开
return ;
WORD sign=0xfeff;
wfile.Write(&sign,2);
}else
if (!wfile.Open(filePath,CFile::modeWrite|CFile::modeNoTruncate|CFile::typeBinary))
return ;
WORD sign;
wfile.SeekToBegin();
wfile.Read(&sign,2);
if (sign!=0xfeff)
{
AfxMessageBox(L"不是UNICODE文档");
return;
}
wfile.SeekToEnd();
CString str=L"添加到文档末尾";
wfile.Write(str.GetBuffer(),str.GetLength()*2);
str.ReleaseBuffer();
wfile.Close();
二 读文档:
1 使用Read函数 读取文档 ,并将读取到的内容转换为CString 以方便处理
CString filepath;
CStdioFile wfile;
filepath=L"c:\test.txt";
if (!wfile.Open(filepath,CFile::modeRead|CFile::typeBinary))
{
AfxMessageBox(L"无法打开文件");
return ;
}
ULONGLONG len=wfile.GetLength();
byte *pByte=NULL;
if (len>0)
{
pByte=new byte[len];
memset(pByte,0,len*sizeof(byte));
WORD sign;
wfile.SeekToBegin();
wfile.Read(&sign,2);
if (sign!=0xfeff)
{
AfxMessageBox(L"录入文件不是Unicode");
}else{
wfile.Read(pByte,len-2);
}
}else{
AfxMessageBox(L"文件长度为0 ");
return;
}
CString buf=(WCHAR*)pByte; // 将数组转换为 CString类型
wfile.Close();
// 其他操作
//...
//
delete [] pByte; // 释放资源
2 使用 ReadString 读取一行文本
virtual LPTSTR ReadString( LPTSTR lpsz, UINT nMax ); virtual BOOL ReadString( CString& rString );
// 读取到换行符n为止,且读取的字符少于nMax-1时,将换行符 n 保存到缓冲区中
Reading is stopped by the first newline character. If, in that case, fewer than nMax–1 characters have been read, a newline character is stored in the buffer. A null character ('