C++ Utilities  4.6.1
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 <windows.h>
6 # include <fcntl.h>
7 # include <sys/stat.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 void NativeFileStream::open(const string &path, ios_base::openmode flags)
30 {
31  // convert path to UTF-16
32  int requiredSize = MultiByteToWideChar(CP_UTF8, 0, path.data(), -1, nullptr, 0);
33  if(requiredSize <= 0) {
34  ::IoUtilities::throwIoFailure("Unable to calculate buffer size for conversion of path to UTF-16");
35  }
36  auto widePath = make_unique<wchar_t[]>(static_cast<size_t>(requiredSize));
37  requiredSize = MultiByteToWideChar(CP_UTF8, 0, path.data(), -1, widePath.get(), requiredSize);
38  if(requiredSize <= 0) {
39  ::IoUtilities::throwIoFailure("Unable to convert path to UTF-16");
40  }
41  // translate flags
42  int nativeFlags = (flags & ios_base::binary ? _O_BINARY : 0);
43  int permissions = 0;
44  if((flags & ios_base::out) && (flags & ios_base::in)) {
45  nativeFlags |= _O_RDWR;
46  } else if(flags & ios_base::out) {
47  nativeFlags |= _O_WRONLY | _O_CREAT;
48  permissions = _S_IREAD | _S_IWRITE;
49  } else if(flags & ios_base::in) {
50  nativeFlags |= _O_RDONLY;
51  }
52  if(flags & ios_base::trunc) {
53  nativeFlags |= _O_TRUNC;
54  }
55  // initialize stdio_filebuf
56  int fd = _wopen(widePath.get(), nativeFlags, permissions);
57  if(fd == -1) {
58  ::IoUtilities::throwIoFailure("_wopen failed");
59  }
60  m_filebuf = make_unique<__gnu_cxx::stdio_filebuf<char> >(fd, flags);
61  rdbuf(m_filebuf.get());
62 }
63 
64 void NativeFileStream::close()
65 {
66  if(m_filebuf) {
67  m_filebuf->close();
68  }
69 }
70 
71 #endif
72 
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