用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 }

 

你可能感兴趣的:(File类)