Getting better error messages for iostreams

筅森魡賤 提交于 2019-12-12 05:58:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!