In the use of C + + for file reading and writing process, whether for binary files or text files need to do exception processing, in C + + we can use CFile for file read and write, but in MFC can also use CStdioFile to read and write files.
The exception handling in the process of reading a text file using CFile can be implemented by the following code
CString m_strfilename = "Test.txt"; CFile M_file; CFileException ex;if (!m_file.open (M_strfilename,cfile::moderead | Cfile::sharedenywrite, &ex) {TCHAR Szerror[1024];ex. GetErrorMessage (szerror,1024); AfxMessageBox (szerror); return;} else{}
If an error occurs during file reading, the program pops up a dialog box to alert the user and aborts the program. The code for the write text file is as follows
CString m_strfilename = "Test.txt"; CFile M_file; CFileException ex;if (!m_file.open (m_strfilename,cfile::modecreate | Cfile::modewrite | Cfile::shareexclusive, &ex) {TCHAR Szerror[1024];ex. GetErrorMessage (szerror,1024); AfxMessageBox (szerror); return;} else{}
The code to write the binary file is as follows
CString m_strfilename = "Test"; CFile M_file; CFileException ex;if (!m_file.open (m_strfilename,cfile::modecreate | Cfile::modewrite | cfile::shareexclusive | Cfile::typebinary, &ex) {TCHAR Szerror[1024];ex. GetErrorMessage (szerror,1024); AfxMessageBox (szerror); return;} else{}
Second-class read the same as the text file read the same as just add cfile::typebinary, so whether it is read or write to the file if there is any problem in the process, will give the user pop up a reminder dialog box, tell the user error!
For CStdioFile in the process of reading and writing the exception mechanism is the same as CFile, here is not to repeat.
Exception handling mechanism in C + + in the process of reading and writing files