This is the simplest example of a memory allocation instance that has never been used by itself, which is an instance of itself from an unsaved file, which is an instance of a memory error */ The following code dumps the contents of the file into other files note the following points here: 1. Try to understand capturing open file exceptions and know how to catch exceptions 2. How to dynamically allocate memory space and Release 3 after use. How to correctly use the file dialog box provided by MFC */ / /The following code is: Dump the contents of the file into another specified file Void cmydlg::onsavebutton () { // TODO: Add your Control notification handler code here cfile file; cstring m_path= "D:\ \test.txt "; if (!file. Open (M_path,cfile::moderead)) { messagebox ("opening file error1!"); return ; } int len=file. GetLength (); // char* buffer=new char[len+1];//prone to buffer overflow the problem is that the following uses buffer[len]= ' + '; Have reminded themselves again of if (!buffer) { messagebox ("allocating fail!"); return; } else {// carefully examine how the program implements exception handling for files try { file. Read (Buffer,len); } catch (cfileexception* e) { MessageBox ("Reading fiLe error "); file. Close (); e->delete (); return ; } // buffer[len]= ' + '; } file. Close (); m_path= "D:\\total.txt"; if (!file. Open (m_path,cfile::modewrite| cfile::modecreate)) { messagebox ("Opening file error2"); return ; } file. Seektoend ();//point the file pointer to the end of the file and write file. Write (Buffer,len); file. Close (); delete buffer;} //open file, read into edit box Void cmydlg::onread () { // TODO: Add your control Notification handler code here cfile file; if (!file. Open ("D:\\test.txt", Cfile::moderead)) { messagebox ("opening file error!"); return ; } int len=file. GetLength (); char* buffer=new char[len+1]; if (!buffer) { messagebox (" Allocating fail "); return ; } else { try { file. Read (Buffer,len); } catch (cfileexception* e) { MessageBox ("Reading file error"); file. Close (); e->delete (); return; } } buffer[len]= ' + '; m_note=buffer; delete buffer; file. Close (); updatedata (FALSE);} Void cmydlg::onsavepath () { // todo: add your control notification handler code here cstring msg= "File save error"; CFileDialog dlg (True, "TXT", Null,null, "Text file (*.txt) |*. TXT "); //cfiledialog dlg (true,null,null,null,null); if (dlg. DoModal () ==idok) { m_path=dlg. GetPathName (); } else { messagebox (msg); }}
Message Board Programming (CFile function and dynamic Assignment)