Exception handling mechanism in C + + in the process of reading and writing files

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.