Notes for C ++ File Operations

Source: Internet
Author: User

1. After opening a file, remember to check whether the file is successfully opened.

This is not only a good habit, but also for usProgramDebugging is also very helpful. Otherwise, we will not find out why the program did not come up with the expected results after a long time. Finally, we found that the original file was not opened .. I am sorry .. Haha.

2. If you want to reuse an existing stream object, remember to close and clear the file stream after each file is used up. ①   Why is it necessary to close the file stream? When we open a file stream, it first checks the file stream status. If it is already in the open status, it sets the internal status and indicates that an error has occurred, any attempt to use the file stream will fail. ②   Why do we need to clear the file stream?   Because when we use a file stream, the file stream may end with a file Terminator because it reaches the end of the file. Or end with an error. The file stream is invalid. If the clear function is not used to reset the stream status, any subsequent operations on the file stream will be invalid .. 3 if we are writing a program for processing file streams, we also need to pay attention to the first point. For example, void read (ifstream & in, const string & file ){ In. Open (file. c_str ()); While (! In. EOF ()) { ....... } }   Let's analyze whether this function will make an error .. Maybe, we don't know what the previous status of the passed Stream object is? If the stream object is in the normal state, of course, no problem. If the stream object is in an invalid state, we cannot use this function... Similarly, we do not know whether the stream object is in the open state. If it is in the open state, our subsequent operations are also invalid. Therefore, we should write this function as follows: void read (ifstream & in, const string & file ){ Cin. Close (); Cin. Clear (); In. Open (file. c_str ()); While (! In. EOF ()) { ....... } }

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.