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