I have been studying files for a while, but actually we see so many different things on the web to do (it seems) the same thing sometimes. Many people suggest to do a thing, others another one. I would like to know the unforgettable rules to apply always to files, in what circumstances, ecc. For example:
0. Of course we have always to close the file. (I don't mention explicitly the opposite).
1. Is always a good programming practice to control if a file is open (with the function is_open())?
2. If we control if a file is open, should we control also if it's good or is not bad, or something like that?
3. To get all the file content, we can use getline, until the eofbit is not set, but is it the best thing to do?
Well, we see many things like that around the web, but what are the best programming practices to manage files?
0. We do not have to close C++ file streams because they are closed automatically in destructor. However we cannot check if file is there was an error during closing that way.
1. Yes. It is a good practice. Because file might be not here, you do not have permisssions, etc.
2. C++ fsream is that: a stream. Anything applying to generic streams (including cin and cout) applies to file streams too. It is always a good idea to check stream state.
3. getline was not created to get all file content, and in case of generic binary file it cannot be used that way. Depending on purpose you might select different strategies, but in general case you do not want whole file (which can be gygabites in size) in memory. .read() member function is usually used.
You should always remember that with files more things can go wrong: there could not be enough space, you can have unsufficient permissions, file can be locked by AV software or deleted by user in process.
Also streams are buffered, so in case your program crashes you are not guaranteed that everything you written to this point will be actually written (and in case of some filesystems that file will be actually here)
But do you suggest to always use the try-catch construct when we are talking about managing files or there's a situation where the try-catch is unnecessary?
Is this correct for example?
you recommend just to use the default version and check for fail/bad bit?
Usually, yes.
Many operations sets failbit as part of their normal function. There is sense in setting program to throw exception on badbit because usually it is fatal error in depth of implementation and is usually unrecoverable.