C++ Utilities  4.11.0
Common C++ classes and routines used by my applications such as argument parser, IO and conversion utilities
nativefilestream.cpp
Go to the documentation of this file.
1 #include "./nativefilestream.h"
2 
3 #ifdef PLATFORM_MINGW
4 #include "catchiofailure.h"
5 #include <fcntl.h>
6 #include <sys/stat.h>
7 #include <windows.h>
8 #endif
9 
10 using namespace std;
11 
12 namespace IoUtilities {
13 
14 #if !defined(PLATFORM_MINGW) || !defined(CPP_UTILITIES_USE_NATIVE_FILE_BUFFER)
15 
16 // just use std::fstream
17 
18 #else
19 
21  : m_filebuf(new __gnu_cxx::stdio_filebuf<char>)
22 {
23  rdbuf(m_filebuf.get());
24 }
25 
26 NativeFileStream::~NativeFileStream()
27 {
28 }
29 
30 void NativeFileStream::open(const string &path, ios_base::openmode flags)
31 {
32  // convert path to UTF-16
33  int requiredSize = MultiByteToWideChar(CP_UTF8, 0, path.data(), -1, nullptr, 0);
34  if (requiredSize <= 0) {
35  ::IoUtilities::throwIoFailure("Unable to calculate buffer size for conversion of path to UTF-16");
36  }
37  auto widePath = make_unique<wchar_t[]>(static_cast<size_t>(requiredSize));
38  requiredSize = MultiByteToWideChar(CP_UTF8, 0, path.data(), -1, widePath.get(), requiredSize);
39  if (requiredSize <= 0) {
40  ::IoUtilities::throwIoFailure("Unable to convert path to UTF-16");
41  }
42  // translate flags
43  int nativeFlags = (flags & ios_base::binary ? _O_BINARY : 0);
44  int permissions = 0;
45  if ((flags & ios_base::out) && (flags & ios_base::in)) {
46  nativeFlags |= _O_RDWR;
47  } else if (flags & ios_base::out) {
48  nativeFlags |= _O_WRONLY | _O_CREAT;
49  permissions = _S_IREAD | _S_IWRITE;
50  } else if (flags & ios_base::in) {
51  nativeFlags |= _O_RDONLY;
52  }
53  if (flags & ios_base::trunc) {
54  nativeFlags |= _O_TRUNC;
55  }
56  // initialize stdio_filebuf
57  int fd = _wopen(widePath.get(), nativeFlags, permissions);
58  if (fd == -1) {
59  ::IoUtilities::throwIoFailure("_wopen failed");
60  }
61  m_filebuf = make_unique<__gnu_cxx::stdio_filebuf<char>>(fd, flags);
62  rdbuf(m_filebuf.get());
63 }
64 
65 void NativeFileStream::close()
66 {
67  if (m_filebuf) {
68  m_filebuf->close();
69  }
70 }
71 
72 #endif
73 }
CPP_UTILITIES_EXPORT void throwIoFailure(const char *what)
Throws a std::ios_base::failure with the specified message.
STL namespace.
Contains utility classes helping to read and write streams.
Definition: binaryreader.h:10
std::fstream NativeFileStream