Imported Upstream version 0.7.5
[platform/upstream/libsolv.git] / win32 / fmemopen.c
1 #include <stdio.h>
2 #include <io.h>
3 #include <fcntl.h>
4 #include <windows.h>
5
6 FILE *
7 fmemopen(void *buf, size_t size, const char *mode)
8 {
9   char temppath[MAX_PATH + 1];
10   char tempnam[MAX_PATH + 1];
11   DWORD l;
12   HANDLE fh;
13   FILE *fp;
14
15   if (strcmp(mode, "r") != 0 && strcmp(mode, "r+") != 0)
16     return 0;
17   l = GetTempPath(MAX_PATH, temppath);
18   if (!l || l >= MAX_PATH)
19     return 0;
20   if (!GetTempFileName(temppath, "solvtmp", 0, tempnam))
21     return 0;
22   fh = CreateFile(tempnam, DELETE | GENERIC_READ | GENERIC_WRITE, 0,
23                   NULL, CREATE_ALWAYS,
24                   FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE,
25                   NULL);
26   if (fh == INVALID_HANDLE_VALUE)
27     return 0;
28   fp = _fdopen(_open_osfhandle((intptr_t)fh, 0), "w+b");
29   if (!fp)
30     {
31       CloseHandle(fh);
32       return 0;
33     }
34   if (buf && size && fwrite(buf, size, 1, fp) != 1)
35     {
36       fclose(fp);
37       return 0;
38     }
39   rewind(fp);
40   return fp;
41 }