MFC中的文件操作

这两天一直在搞文件的新建、打开、保存以及一些简单的读写操作,虽然简单,但是对我这新手来说,还真有点难度哈,最后终于搞定了,在此整理一下,即便别人可能看不到,对自己的成长也是有好处的吧哈。

 

///

//功能:新建一个记事本,同时添加一条空白记录到记事本文件中

//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;
 }

 

 

现在在弄另一个添加记录的功能,等做好以后,再整理代码发上来哈

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值