问题
I implemented a small program that can extract (and via fuse mount) a certain archive format. I use boost::filesystem::ifstream
, but on error (e.g. the file a user wants to extract does not exist) I get very nondescript error messages. I wonder is there a way to get better error messages for IO related problems in C++?
On a related note I wonder whether I should have used C's FILE*
or in the case of the fuse filesystem just plain file descriptors? Because strerror(errno)
is way better than what iostreams are giving me.
回答1:
We couldn't find any better way than using boost::iostreams and implementing our own file-based sink and source.
If you want, you can grab the source code here (Apache-licensed):
http://sourceforge.net/projects/cgatools/files/1.3.0/cgatools-1.3.0.9-source.tar.gz/download
the relevant files are:
cgatools/util/Streams.[ch]pp
回答2:
Since your using the filesystem library anyway, you could test to see if the file exists prior to trying to access it with a stream. This would avoid your bloat concerns, but it would not operate in the same sense as what you're looking for, i.e. the stream itself would not perform the existence check.
However, since you are using boost::filesystem::ifstream
, I'm assuming that you are using that because you are using boost::filesystem::path
. In boost's implementation of ifstream, they inherit from std::basic_ifstream
and override two functions: the constructor and open
. So, if you want better error reporting you could simply do they same thing, inherit from boost's implementation and override those two functions to provide the checking you wish. Additional bloat: probably not a lot, and it incorporates the behavior you wish into the stream itself.
来源:https://stackoverflow.com/questions/6065532/getting-better-error-messages-for-iostreams