1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
|
#include "./nativefilestream.h"
#ifdef CPP_UTILITIES_USE_NATIVE_FILE_BUFFER
/*!
* \class
* So one gets e.g. "open failed: Permission denied" instead of
just "open failed: iostream error".
*/
/*!
* \class NativeFileStream
* \brief Provides a standard IO stream instantiated using native APIs.
*
* Using this class instead of `std::fstream` has the following benefits:
* - Under Windows, the specified file path is interpreted as UTF-8 and passed to Windows' unicode API
* to support any kind of non-ASCII characters in file paths.
* - It is possible to open a file from a native file descriptor. This is for instance useful when dealing with
* Android's `content://` URLs.
* - Better error messages at least when opening a file, e.g. "Permission denied" instead of just "basic_ios::clear".
*/
#ifdef PLATFORM_WINDOWS
#include "../conversion/stringconversion.h"
#endif
// include header files for file buffer implementation
#if defined(CPP_UTILITIES_USE_GNU_CXX_STDIO_FILEBUF)
#include <ext/stdio_filebuf.h>
#elif defined(CPP_UTILITIES_USE_BOOST_IOSTREAMS)
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#else
#error "Configuration for NativeFileStream backend insufficient."
#endif
// include platform specific header
#if defined(PLATFORM_UNIX)
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#elif defined(PLATFORM_WINDOWS)
#include <fcntl.h>
#include <io.h>
#include <limits>
#include <sys/stat.h> // yes, this is needed under Windows (https://msdn.microsoft.com/en-US/library/5yhhz3y7.aspx)
#include <windows.h>
#ifdef max
#undef max // see explanation in stringconversion.cpp
#endif
#endif
#endif
using namespace std;
namespace CppUtilities {
#ifdef CPP_UTILITIES_USE_NATIVE_FILE_BUFFER
#ifdef CPP_UTILITIES_USE_GNU_CXX_STDIO_FILEBUF
using StreamBuffer = __gnu_cxx::stdio_filebuf<char>;
#else // CPP_UTILITIES_USE_BOOST_IOSTREAMS
using StreamBuffer = boost::iostreams::stream_buffer<boost::iostreams::file_descriptor>;
#endif
struct NativeFileParams {
#ifdef PLATFORM_WINDOWS
NativeFileParams(ios_base::openmode cppOpenMode)
: openMode(cppOpenMode & ios_base::binary ? _O_BINARY : 0)
, flags(cppOpenMode & ios_base::binary ? 0 : _O_TEXT)
, permissions(0)
, access(0)
, shareMode(0)
, creation(0)
{
if ((cppOpenMode & ios_base::out) && (cppOpenMode & ios_base::in)) {
openMode |= _O_RDWR;
access = GENERIC_READ | GENERIC_WRITE;
shareMode = FILE_SHARE_READ;
creation = OPEN_EXISTING;
} else if (cppOpenMode & ios_base::out) {
openMode |= _O_WRONLY | _O_CREAT;
permissions = _S_IREAD | _S_IWRITE;
access = GENERIC_WRITE;
creation = OPEN_ALWAYS;
} else if (cppOpenMode & ios_base::in) {
openMode |= _O_RDONLY;
flags |= _O_RDONLY;
access = GENERIC_READ;
shareMode = FILE_SHARE_READ;
creation = OPEN_EXISTING;
}
if (cppOpenMode & ios_base::app) {
openMode |= _O_APPEND;
flags |= _O_APPEND;
}
if (cppOpenMode & ios_base::trunc) {
openMode |= _O_TRUNC;
creation = (cppOpenMode & ios_base::in) ? TRUNCATE_EXISTING : CREATE_ALWAYS;
}
}
int openMode;
int flags;
int permissions;
DWORD access;
DWORD shareMode;
DWORD creation;
#else
NativeFileParams(ios_base::openmode cppOpenMode)
: openFlags(0)
{
if ((cppOpenMode & ios_base::in) && (cppOpenMode & ios_base::out)) {
if (cppOpenMode & ios_base::app) {
openMode = "a+";
openFlags = O_RDWR | O_APPEND;
} else if (cppOpenMode & ios_base::trunc) {
openMode = "w+";
openFlags = O_RDWR | O_TRUNC;
} else {
openMode = "r+";
openFlags = O_RDWR;
}
} else if (cppOpenMode & ios_base::in) {
openMode = 'r';
openFlags = O_RDONLY;
} else if (cppOpenMode & ios_base::out) {
if (cppOpenMode & ios_base::app) {
openMode = 'a';
openFlags = O_WRONLY | O_APPEND;
} else if (cppOpenMode & ios_base::trunc) {
openMode = 'w';
openFlags = O_WRONLY | O_TRUNC | O_CREAT;
} else {
openMode = "w";
openFlags = O_WRONLY | O_CREAT;
}
}
if (cppOpenMode & ios_base::binary) {
openMode += 'b';
}
}
std::string openMode;
int openFlags;
#endif
};
/*!
* \class NativeFileStream::FileBuffer
* \brief The NativeFileStream::FileBuffer class holds an std::basic_streambuf<char> object obtained from a file path or a native file descriptor.
*/
/*!
* \brief Constructs a new FileBuffer object taking ownership of \a buffer.
*/
NativeFileStream::FileBuffer::FileBuffer(std::basic_streambuf<char> *buffer)
: buffer(buffer)
{
}
/*!
* \brief Opens a file buffer from the specified \a path.
* \remarks See NativeFileStream::open() for remarks on how \a path must be encoded.
*/
NativeFileStream::FileBuffer::FileBuffer(const char *path, ios_base::openmode openMode)
{
#ifdef PLATFORM_WINDOWS
// convert path to UTF-16
const auto widePath(makeWidePath(path));
#endif
// compute native params
const NativeFileParams nativeParams(openMode);
// open native file handle or descriptor
#ifdef CPP_UTILITIES_USE_GNU_CXX_STDIO_FILEBUF
#ifdef PLATFORM_WINDOWS
descriptor = _wopen(widePath.get(), nativeParams.openMode, nativeParams.permissions);
if (descriptor == -1) {
throw std::ios_base::failure("_wopen failed", std::error_code(errno, std::system_category()));
}
#else
descriptor = ::open(path, nativeParams.openFlags, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (descriptor == -1) {
throw std::ios_base::failure("open failed", std::error_code(errno, std::system_category()));
}
#endif
buffer = make_unique<StreamBuffer>(descriptor, openMode);
#else // CPP_UTILITIES_USE_BOOST_IOSTREAMS
#ifdef PLATFORM_WINDOWS
handle = CreateFileW(widePath.get(), nativeParams.access, nativeParams.shareMode, nullptr, nativeParams.creation, FILE_ATTRIBUTE_NORMAL, nullptr);
if (handle == INVALID_HANDLE_VALUE) {
throw std::ios_base::failure("CreateFileW failed", std::error_code(static_cast<int>(GetLastError()), std::system_category()));
}
buffer = std::make_unique<StreamBuffer>(handle, boost::iostreams::close_handle);
// if we wanted to open assign the descriptor as well: descriptor = _open_osfhandle(reinterpret_cast<std::intptr_t>(handle), nativeParams.flags);
#else
descriptor = ::open(path, nativeParams.openFlags, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (descriptor == -1) {
throw std::ios_base::failure("open failed", std::error_code(errno, std::system_category()));
}
buffer = make_unique<StreamBuffer>(descriptor, boost::iostreams::close_handle);
#endif
#endif
}
/*!
* \brief Opens a file buffer from the specified \a path.
* \remarks See NativeFileStream::open() for remarks on how \a path must be encoded.
*/
NativeFileStream::FileBuffer::FileBuffer(const std::string &path, ios_base::openmode openMode)
: NativeFileStream::FileBuffer(path.data(), openMode)
{
}
/*!
* \brief Opens a file buffer from the specified \a fileDescriptor.
* \remarks
* The specified \a openMode is only used when using __gnu_cxx::stdio_filebuf<char> and must be in accordance with how \a fileDescriptor
* has been opened.
*/
NativeFileStream::FileBuffer::FileBuffer(int fileDescriptor, ios_base::openmode openMode)
: descriptor(fileDescriptor)
{
#ifdef CPP_UTILITIES_USE_GNU_CXX_STDIO_FILEBUF
buffer = make_unique<StreamBuffer>(descriptor, openMode);
#else // CPP_UTILITIES_USE_BOOST_IOSTREAMS
CPP_UTILITIES_UNUSED(openMode)
#ifdef PLATFORM_WINDOWS
handle = reinterpret_cast<Handle>(_get_osfhandle(descriptor));
buffer = make_unique<StreamBuffer>(handle, boost::iostreams::close_handle);
#else
buffer = make_unique<StreamBuffer>(descriptor, boost::iostreams::close_handle);
#endif
#endif
}
/*!
* \brief Constructs a new NativeFileStream which is initially closed.
*/
NativeFileStream::NativeFileStream()
: iostream(new StreamBuffer)
, m_data(rdbuf())
{
}
/*!
* \brief Moves the NativeFileStream.
*/
NativeFileStream::NativeFileStream(NativeFileStream &&other)
: iostream(other.m_data.buffer.release())
, m_data(rdbuf())
{
#ifdef PLATFORM_WINDOWS
m_data.handle = other.m_data.handle;
#endif
m_data.descriptor = other.m_data.descriptor;
}
/*!
* \brief Destroys the NativeFileStream releasing all underlying resources.
*/
NativeFileStream::~NativeFileStream()
{
}
/*!
* \brief Returns whether the file is open.
*/
bool NativeFileStream::isOpen() const
{
return m_data.buffer && static_cast<const StreamBuffer *>(m_data.buffer.get())->is_open();
}
/*!
* \brief Opens the file referenced by \a path with the specified \a openMode.
* \remarks
* - Under Windows \a path is expected to be UTF-8 encoded. It is automatically converted so non-ASCII
* characters are treated correctly under Windows (in contrast to std::fstream::open() where only the
* current code page is supported).
* - Under other platforms the \a path is just passed through so there are no assumptions made about its
* encoding.
* \todo Maybe use setstate() instead of throwing exceptions directly for consistent error handling
* with std::fstream::open(). However, that makes passing specific error messages difficult.
*/
void NativeFileStream::open(const char *path, ios_base::openmode openMode)
{
setData(FileBuffer(path, openMode), openMode);
}
/*!
* \brief Opens the file referenced by \a path with the specified \a openMode.
*/
void NativeFileStream::open(const std::string &path, ios_base::openmode openMode)
{
open(path.data(), openMode);
}
/*!
* \brief Opens the file from the specified \a fileDescriptor with the specified \a openMode.
* \throws Throws std::ios_base::failure in the error case.
* \todo
* - Maybe use setstate() instead of throwing exceptions directly for consistent error handling
* with std::fstream::open(). However, that makes passing specific error messages difficult.
*/
void NativeFileStream::open(int fileDescriptor, ios_base::openmode openMode)
{
setData(FileBuffer(fileDescriptor, openMode), openMode);
}
/*!
* \brief Closes the file if opened; otherwise does nothing.
*/
void NativeFileStream::close()
{
if (m_data.buffer) {
static_cast<StreamBuffer *>(m_data.buffer.get())->close();
#ifdef PLATFORM_WINDOWS
m_data.handle = nullptr;
#endif
m_data.descriptor = -1;
}
}
/*!
* \brief Internally called to assign the buffer, file descriptor and handle.
*/
void NativeFileStream::setData(FileBuffer data, std::ios_base::openmode openMode)
{
rdbuf(data.buffer.get());
m_data = std::move(data);
m_openMode = openMode;
#if defined(PLATFORM_WINDOWS) && defined(CPP_UTILITIES_USE_BOOST_IOSTREAMS)
// workaround append flag dysfunctioning
if (m_openMode & ios_base::app) {
seekp(0, ios_base::end);
}
#endif
}
#ifdef PLATFORM_WINDOWS
/*!
* \brief Converts the specified UTF-8 encoded \a path to UTF-16 for passing it to WinAPI functions.
* \throws Throws std::ios_base::failure when an encoding error occurs.
*/
std::unique_ptr<wchar_t[]> NativeFileStream::makeWidePath(std::string_view path)
{
auto ec = std::error_code();
auto size = path.size() < static_cast<std::size_t>(std::numeric_limits<int>::max() - 1) ? static_cast<int>(path.size() + 1) : -1;
auto widePath = ::CppUtilities::convertMultiByteToWide(ec, path.data(), size);
if (!widePath.first) {
throw std::ios_base::failure("converting path to UTF-16", ec);
}
return std::move(widePath.first);
}
/*!
* \brief Converts the specified UTF-8 encoded \a path to UTF-16 for passing it to WinAPI functions.
* \throws Throws std::ios_base::failure when an encoding error occurs.
*/
std::unique_ptr<wchar_t[]> NativeFileStream::makeWidePath(const std::string &path)
{
return makeWidePath(std::string_view(path));
}
#endif
#else
// std::fstream is used
#endif
} // namespace CppUtilities
|