这两天一直在搞文件的新建、打开、保存以及一些简单的读写操作,虽然简单,但是对我这新手来说,还真有点难度哈,最后终于搞定了,在此整理一下,即便别人可能看不到,对自己的成长也是有好处的吧哈。
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//功能:新建一个记事本,同时添加一条空白记录到记事本文件中
//DATA:6/9/2009
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
CFileDialog fileDlg (TRUE,_T("jsp"),_T("*.jsp"),
OFN_OVERWRITEPROMPT,_T("Create NewDocment(*.jsp) | *.jsp |"),NULL);
CString PathName;
if (fileDlg.DoModal()==IDOK)
{
PathName=fileDlg.GetPathName();
CFile file;
CFileException err;
if (file.Open(PathName,CFile::modeReadWrite | CFile::modeCreate | CFile::modeNoTruncate,&err))
{
//创建新记事本文件成功,并自动添加一条记录
CString m_strRecordCon;
wchar_t *endptr;
char strUser[1000];
int nLength=0;
wcstombs(strUser, m_strRecordCon, 1000);
nLength = min(strlen(strUser), 1000);
file.Write(strUser,nLength);
if (nLength=0)
{
AfxMessageBox(L"写入记录失败!请点击'新建记录'重试!");
}
memset(strUser,0,sizeof(strUser));
UpdateData(FALSE);
}
else
{
AfxMessageBox(_T("创建文件失败!"));
err.ReportError();
err.Delete();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//功能:打开记事本文件
//DATA:6/9/2009
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
CFileDialog dlg(TRUE,NULL,NULL, OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
L"Data Documents(*.jsp)|*.jsp|",AfxGetMainWnd());
CString strTem;
if(dlg.DoModal()==IDOK)
{
strTem= dlg.GetPathName();//获取路径名
FileName=dlg.GetFileName();//获取文件名
}
CFile file;
//CString FileName=strTem;
AfxMessageBox(FileName);
char buf[1000];
memset(buf,0,1000); //初始化内存,防止读出字符末尾出现乱码
if(!file.Open(strTem,CFile::modeReadWrite))
{
//MessageBox(L"没有选择文件!");
return;
}
file.Read(buf,sizeof(buf));
file.Close();
m_strRecordCon=buf;
//如果文件字节数大于400,则弹出提醒对话框
if (m_strRecordCon.GetLength()>400)
{
AfxMessageBox(L"该文件字节数大于400,请另选择文件!");
}
memset(buf,0,sizeof(buf));
UpdateData(FALSE); //将记事本内数据刷新到记录编辑框显示
//////////////////////////////////////////////////////////////////////////////////////
//功能:保存文件
//DATA:6/9/2009
/////////////////////////////////////////////////////////////////////////////////////
CFileDialog fileDlg (FALSE,_T("jsp"),_T("*.jsp"),
OFN_OVERWRITEPROMPT,_T("Data Documents(*.jsp) | *.* |"),this,0 );
CString PathName;
if (fileDlg.DoModal()==IDOK)
{
PathName=fileDlg.GetPathName();
CFile file;
file.Open(PathName, CFile::modeCreate | CFile::modeReadWrite);
//保存用户输入的数据
CString struser;
struser = "";
wchar_t *endptr;
CString strTem;
char *writesz;
writesz = new char[struser.GetLength()+2];
wcstombs(writesz, struser, struser.GetLength()+2);
file.Write(writesz, strlen(writesz));
file.Close();
AfxMessageBox(L"数据保存完毕!/r/n数据保存在:"+PathName);
delete writesz;
}
现在在弄另一个添加记录的功能,等做好以后,再整理代码发上来哈
本文分享了使用C++进行记事本文件的新建、打开与保存操作的实践经验,包括如何处理文件读写异常及数据刷新。
859

被折叠的 条评论
为什么被折叠?



