Ticket #8934: openfile.c

File openfile.c, 1.2 KB (added by jeffrey.beu.uz8yz6yl@…, 9 years ago)

fopen substitute

Line 
1#include <stdio.h>
2#include <stdlib.h>
3
4static const wchar_t prefix[4] = {L'\\',L'\\',L'?',L'\\'};
5static const size_t m = 32768;
6
7static wchar_t* __cdecl c2w(const char *c)
8{
9 size_t l = mbstowcs(NULL,c,0);
10 wchar_t *w = (wchar_t *)calloc(l+1,sizeof(wchar_t));
11
12 if(w == NULL) return NULL;
13
14 if( mbstowcs(w,c,l) == l) {
15 return w;
16 }else {
17 free(w);
18 return NULL;
19 }
20}
21
22static wchar_t* __cdecl c2w_path(const char *c)
23{
24 wchar_t *w = c2w(c);
25 int r = 0;
26
27 if(w == NULL) return NULL;
28
29 r = wcsncmp(w,prefix,4);
30
31 if(0 != r) {
32 wchar_t *ww = (wchar_t *)calloc(m + 4,sizeof(wchar_t));
33
34 if(ww == NULL) {
35 free(w);
36 w = NULL;
37 }else {
38
39 memcpy(ww,prefix,sizeof(prefix));
40
41 if(NULL == _wfullpath(ww+4,w,m)) {
42 free(ww);
43 ww = NULL;
44 }
45
46 free(w);
47 w = ww;
48 }
49 }
50
51 return w;
52}
53
54FILE * __cdecl openfile(const char * path, const char *flags)
55{
56
57 wchar_t* fn = c2w_path(path);
58 wchar_t* fg = NULL;
59 FILE *fp = NULL;
60
61 if(fn == NULL) return NULL;
62
63 fg = c2w(flags);
64
65 if(fg == NULL) {
66 free(fn);
67 return NULL;
68 }
69
70 fp = _wfopen(fn,fg);
71
72 free(fg);
73 free(fn);
74
75 return fp;
76}