• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Fcoding_狂人
自由 编码 Fcoding
博客园    首页    新随笔    联系   管理     

用CFile类简单读写文件

用CFile类简单读写文件 

 

 1 //读文件数据
 2 void CFileOperDlg::OnButtonRead() 
 3 {
 4  // TODO: Add your control notification handler code here
 5 
 6  CFile file;
 7  CString FileName="data.txt";
 8  char buf[1000];//读1K
 9  memset(buf,0,1000);//初始化内存,防止读出字符末尾出现乱码
10  try
11  {
12   if(!file.Open(FileName,CFile::modeRead))
13   {
14    MessageBox("没有文件!");
15    return;
16   }
17   file.Read(buf,sizeof(buf));
18   file.Close();
19   m_data=buf;//给文本框赋值CString m_data
20   UpdateData(false);//在文本框显示
21   MessageBox("读出成功!");
22  }
23  catch(CFileException *e)
24  {
25   CString str;
26   str.Format("读取数据失败的原因是:%d",e->m_cause);
27   MessageBox("str");
28   file.Abort();
29   e->Delete();
30  }
31 }
32 //写文件数据
33 void CFileOperDlg::OnButtonWrite() 
34 {
35  // TODO: Add your control notification handler code here
36  UpdateData();//取文本框字符
37  CFile file;
38  CString FileName="data.txt";
39  try
40  {
41   file.Open(FileName,CFile::modeCreate|CFile::modeWrite);
42   file.SeekToBegin();
43   file.Write((unsigned char *)(m_data.GetBuffer(0)),m_data.GetLength());//CString m_data
44   file.Flush();
45   file.Close();
46   MessageBox("写入成功!");
47  }
48  catch(CFileException *e)
49  {
50   CString str;
51   str.Format("写入失败的原因是:%d",e->m_cause);
52   MessageBox("str");
53   file.Abort();
54   e->Delete();
55  }
56 }

 

posted @ 2012-06-29 20:54  Fcoding_狂人  阅读(24618)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3