1 #include "brio.h"
2 #include <stdio.h>
3 
4 #ifdef _WIN32
5 #include <windows.h>
6 #endif
7 
8 // This is needed to support wide character paths on windows
open_with_widechar_on_windows(SEXP path,const char * mode)9 FILE* open_with_widechar_on_windows(SEXP path, const char* mode) {
10   FILE* out;
11 #ifdef _WIN32
12   const char* path_c = Rf_translateCharUTF8(path);
13   // First convert the mode to the wide equivalent
14   // Only usage is 2 characters so max 8 bytes + 2 byte null.
15   wchar_t mode_w[10];
16   MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_w, 9);
17 
18   // Then convert the path
19   wchar_t* buf;
20   size_t len = MultiByteToWideChar(CP_UTF8, 0, path_c, -1, NULL, 0);
21   if (len <= 0) {
22     error("Cannot convert file to Unicode: %s", path_c);
23   }
24   buf = (wchar_t*)R_alloc(len, sizeof(wchar_t));
25   if (buf == NULL) {
26     error("Could not allocate buffer of size: %ll", len);
27   }
28 
29   MultiByteToWideChar(CP_UTF8, 0, path_c, -1, buf, len);
30   out = _wfopen(buf, mode_w);
31 #else
32   out = fopen(Rf_translateChar(path), mode);
33 #endif
34 
35   return out;
36 }
37