I am using the standard C++ fstreams library and I am wondering what is the right way to use it. By experience I sort of figured out a small usage protocol, but I am not really sure about it. For the sake of simplicity let's assume that I just want to read a file, e.g., to filter its content and put it on another file. My routine is roughly as follows:
- I declare a local
istream i("filename")
variable to open the file; - I check either
i.good()
ori.is_open()
to handle the case where something went bad when opening, e.g., because the file does not exist; after, I assume that the file exists and that i is ok; - I call
i.peek()
and then againi.good()
ori.eof()
to rule out the case where the file is empty; after, I assume that I have actually something to read; - I use
>>
or whatever to read the file's content, andeof()
to check that I am over; - I do not explicitly close the file - I rely on RAII and keep my methods as short and coherent as I can.
Is it a sane (correct, minimal) routine? In the negative case, how would you fix it? Please note that I am not considering races - synchronization is a different affair.