zenXML
Straightforward C++ XML Processing
|
00001 // ************************************************************************** 00002 // * This file is part of the zenXML project. It is distributed under the * 00003 // * Boost Software License, Version 1.0. See accompanying file * 00004 // * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt. * 00005 // * Copyright (C) 2011 ZenJu (zhnmju123 AT gmx.de) * 00006 // ************************************************************************** 00007 00008 #ifndef ZEN_XML_IO_HEADER_8917640501480763248343343 00009 #define ZEN_XML_IO_HEADER_8917640501480763248343343 00010 00011 #include "string_tools.h" 00012 #include "loki/ScopeGuard.h" 00013 #include "zenxml_error.h" 00014 #include "string_utf8.h" 00015 #include <cerrno> 00016 00017 namespace zen 00018 { 00024 #if !defined(ZEN_PLATFORM_WINDOWS) && !defined(ZEN_PLATFORM_OTHER) 00025 #error Please specify your platform: #define ZEN_PLATFORM_WINDOWS or ZEN_PLATFORM_OTHER 00026 #endif 00027 00029 struct XmlFileError : public XmlError 00030 { 00031 typedef int ErrorCode; 00032 00033 XmlFileError(ErrorCode ec) : lastError(ec) {} 00035 ErrorCode lastError; 00036 }; 00037 00038 00040 00046 template <class String> 00047 void saveStream(const std::string& stream, const String& filename) //throw XmlFileError 00048 { 00049 #ifdef ZEN_PLATFORM_WINDOWS 00050 FILE* handle = ::_wfopen(strBegin(utf8CvrtTo<std::wstring>(filename)), L"wb"); 00051 #else 00052 FILE* handle = ::fopen(utf8CvrtTo<std::string>(filename).c_str(), "w"); 00053 #endif 00054 if (handle == NULL) 00055 throw XmlFileError(errno); 00056 00057 Loki::ScopeGuard dummy = Loki::MakeGuard(::fclose, handle); 00058 (void)dummy; 00059 00060 const size_t bytesWritten = ::fwrite(stream.c_str(), 1, stream.size(), handle); 00061 if (::ferror(handle) != 0) 00062 throw XmlFileError(errno); 00063 00064 assert(bytesWritten == stream.size()); 00065 } 00066 00067 00069 00075 template <class String> 00076 std::string loadStream(const String& filename) //throw XmlFileError 00077 { 00078 #ifdef ZEN_PLATFORM_WINDOWS 00079 FILE* handle = ::_wfopen(strBegin(utf8CvrtTo<std::wstring>(filename)), L"rb"); 00080 #else 00081 FILE* handle = ::fopen(utf8CvrtTo<std::string>(filename).c_str(), "r"); 00082 #endif 00083 if (handle == NULL) 00084 throw XmlFileError(errno); 00085 00086 Loki::ScopeGuard dummy = Loki::MakeGuard(::fclose, handle); 00087 (void)dummy; 00088 00089 std::string stream; 00090 do 00091 { 00092 const size_t BLOCK_SIZE = 10 * 1024; 00093 char buffer[BLOCK_SIZE]; 00094 00095 const size_t bytesRead = ::fread(buffer, 1, BLOCK_SIZE, handle); 00096 if (::ferror(handle)) 00097 throw XmlFileError(errno); 00098 00099 assert(bytesRead <= BLOCK_SIZE); 00100 00101 stream.append(buffer, bytesRead); 00102 } 00103 while (!::feof(handle)); 00104 00105 return stream; 00106 } 00107 } 00108 00109 #endif //ZEN_XML_IO_HEADER_8917640501480763248343343