errinfos.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //Copyright (c) 2006-2009 Emil Dotchevski and Reverge Studios, Inc.
  2. //Distributed under the Boost Software License, Version 1.0. (See accompanying
  3. //file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4. //This example demonstrates the intended use of various commonly used
  5. //error_info typedefs provided by Boost Exception.
  6. #include <boost/exception/errinfo_api_function.hpp>
  7. #include <boost/exception/errinfo_at_line.hpp>
  8. #include <boost/exception/errinfo_errno.hpp>
  9. #include <boost/exception/errinfo_file_handle.hpp>
  10. #include <boost/exception/errinfo_file_name.hpp>
  11. #include <boost/exception/errinfo_file_open_mode.hpp>
  12. #include <boost/exception/info.hpp>
  13. #include <boost/throw_exception.hpp>
  14. #include <boost/shared_ptr.hpp>
  15. #include <boost/weak_ptr.hpp>
  16. #include <stdio.h>
  17. #include <errno.h>
  18. #include <exception>
  19. struct error : virtual std::exception, virtual boost::exception { };
  20. struct file_error : virtual error { };
  21. struct file_open_error: virtual file_error { };
  22. struct file_read_error: virtual file_error { };
  23. boost::shared_ptr<FILE>
  24. open_file( char const * file, char const * mode )
  25. {
  26. if( FILE * f=fopen(file,mode) )
  27. return boost::shared_ptr<FILE>(f,fclose);
  28. else
  29. BOOST_THROW_EXCEPTION(
  30. file_open_error() <<
  31. boost::errinfo_api_function("fopen") <<
  32. boost::errinfo_errno(errno) <<
  33. boost::errinfo_file_name(file) <<
  34. boost::errinfo_file_open_mode(mode) );
  35. }
  36. size_t
  37. read_file( boost::shared_ptr<FILE> const & f, void * buf, size_t size )
  38. {
  39. size_t nr=fread(buf,1,size,f.get());
  40. if( ferror(f.get()) )
  41. BOOST_THROW_EXCEPTION(
  42. file_read_error() <<
  43. boost::errinfo_api_function("fread") <<
  44. boost::errinfo_errno(errno) <<
  45. boost::errinfo_file_handle(f) );
  46. return nr;
  47. }