1 /*
2 * Copyright (C) 2020 Veloman Yunkan
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
11 * warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
12 * NON-INFRINGEMENT. See the GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17 *
18 */
19
20 #include "tools.h"
21
22 #ifdef _WIN32
23 #include <locale>
24 #include <codecvt>
25 #include <windows.h>
26 #include <fileapi.h>
27 #endif
28
29 #include <fcntl.h>
30 #include <sys/stat.h>
31
32 namespace zim
33 {
34
35 namespace unittests
36 {
37
TempFile(const char * name)38 TempFile::TempFile(const char* name)
39 : fd_(-1)
40 {
41 #ifdef _WIN32
42 std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> utfConv;
43 wchar_t cbase[MAX_PATH];
44 const std::wstring wname = utfConv.from_bytes(name);
45 GetTempPathW(MAX_PATH-(wname.size()+2), cbase);
46 //This create a empty file, we just have to open it later
47 GetTempFileNameW(cbase, wname.c_str(), 0, wpath_);
48 path_ = utfConv.to_bytes(wpath_);
49 #else
50 const char* const TMPDIR = std::getenv("TMPDIR");
51 const std::string tmpdir(TMPDIR ? TMPDIR : "/tmp");
52 path_ = tmpdir + "/" + name + "_XXXXXX";
53 auto tmp_fd = mkstemp(&path_[0]);
54 ::close(tmp_fd);
55 #endif
56 }
57
~TempFile()58 TempFile::~TempFile()
59 {
60 close();
61 #ifdef _WIN32
62 DeleteFileW(wpath_);
63 #else
64 unlink(path_.c_str());
65 #endif
66 }
67
fd()68 int TempFile::fd()
69 {
70 if (fd_ == -1) {
71 #ifdef _WIN32
72 fd_ = _wopen(wpath_, _O_RDWR);
73 #else
74 fd_ = open(path_.c_str(), O_RDWR);
75 #endif
76 }
77 return fd_;
78 }
79
close()80 void TempFile::close()
81 {
82 if (fd_ != -1) {
83 ::close(fd_);
84 fd_ = -1;
85 }
86 }
87
88 } // namespace unittests
89
90 } // namespace zim
91