system_failure.hpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
  2. // (C) Copyright 2005-2007 Jonathan Turkanis
  3. // (C) Copyright Jonathan Graehl 2004.
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
  6. // See http://www.boost.org/libs/iostreams for documentation.
  7. // Used by mapped_file.cpp.
  8. #ifndef BOOST_IOSTREAMS_DETAIL_SYSTEM_FAILURE_HPP_INCLUDED
  9. #define BOOST_IOSTREAMS_DETAIL_SYSTEM_FAILURE_HPP_INCLUDED
  10. #if defined(_MSC_VER)
  11. # pragma once
  12. #endif
  13. #include <cstring>
  14. #include <string>
  15. #include <boost/config.hpp>
  16. #include <boost/throw_exception.hpp>
  17. #include <boost/iostreams/detail/config/windows_posix.hpp>
  18. #include <boost/iostreams/detail/ios.hpp> // failure.
  19. #if defined(BOOST_NO_STDC_NAMESPACE) && !defined(__LIBCOMO__)
  20. namespace std { using ::strlen; }
  21. #endif
  22. #ifdef BOOST_IOSTREAMS_WINDOWS
  23. # define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
  24. # include <windows.h>
  25. #else
  26. # include <errno.h>
  27. # include <string.h>
  28. #endif
  29. namespace boost { namespace iostreams { namespace detail {
  30. inline BOOST_IOSTREAMS_FAILURE system_failure(const char* msg)
  31. {
  32. std::string result;
  33. #ifdef BOOST_IOSTREAMS_WINDOWS
  34. DWORD err;
  35. LPVOID lpMsgBuf;
  36. if ( (err = ::GetLastError()) != NO_ERROR &&
  37. ::FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER |
  38. FORMAT_MESSAGE_FROM_SYSTEM,
  39. NULL,
  40. err,
  41. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  42. (LPSTR) &lpMsgBuf,
  43. 0,
  44. NULL ) != 0 )
  45. {
  46. result.reserve(std::strlen(msg) + 2 + std::strlen((LPSTR)lpMsgBuf));
  47. result.append(msg);
  48. result.append(": ");
  49. result.append((LPSTR) lpMsgBuf);
  50. ::LocalFree(lpMsgBuf);
  51. } else {
  52. result += msg;
  53. }
  54. #else
  55. const char* system_msg = errno ? strerror(errno) : "";
  56. result.reserve(std::strlen(msg) + 2 + std::strlen(system_msg));
  57. result.append(msg);
  58. result.append(": ");
  59. result.append(system_msg);
  60. #endif
  61. return BOOST_IOSTREAMS_FAILURE(result);
  62. }
  63. inline BOOST_IOSTREAMS_FAILURE system_failure(const std::string& msg)
  64. { return system_failure(msg.c_str()); }
  65. inline void throw_system_failure(const char* msg)
  66. { boost::throw_exception(system_failure(msg)); }
  67. inline void throw_system_failure(const std::string& msg)
  68. { boost::throw_exception(system_failure(msg)); }
  69. } } } // End namespaces detail, iostreams, boost.
  70. #endif // #ifndef BOOST_IOSTREAMS_DETAIL_SYSTEM_FAILURE_HPP_INCLUDED