-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathlibfmemopen.c
36 lines (35 loc) · 1023 Bytes
/
libfmemopen.c
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
#include <windows.h>
#include <share.h>
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "libfmemopen.h"
/* https://github.com/Arryboom/fmemopen_windows */
FILE *fmemopen(void *buf, size_t len, const char *type)
{
int fd;
FILE *fp;
char tp[MAX_PATH - 13];
char fn[MAX_PATH + 1];
int * pfd = &fd;
int retner = -1;
char tfname[] = "MemTF_";
if (!GetTempPathA(sizeof(tp), tp))
return NULL;
if (!GetTempFileNameA(tp, tfname, 0, fn))
return NULL;
retner = _sopen_s(pfd, fn, _O_CREAT | _O_SHORT_LIVED | _O_TEMPORARY | _O_RDWR | _O_BINARY | _O_NOINHERIT, _SH_DENYRW, _S_IREAD | _S_IWRITE);
if (retner != 0)
return NULL;
if (fd == -1)
return NULL;
fp = _fdopen(fd, "wb+");
if (!fp) {
_close(fd);
return NULL;
}
/*File descriptors passed into _fdopen are owned by the returned FILE * stream.If _fdopen is successful, do not call _close on the file descriptor.Calling fclose on the returned FILE * also closes the file descriptor.*/
fwrite(buf, len, 1, fp);
rewind(fp);
return fp;
}