Skip to content

Commit 4feb799

Browse files
committedSep 14, 2021
Add Windows-specific CreateTempFile() implementation
Once again MSVC is the only compiler not supporting basic POSIX functionality.
1 parent b480a3e commit 4feb799

File tree

1 file changed

+27
-13
lines changed

1 file changed

+27
-13
lines changed
 

Diff for: ‎src/filesys.cpp

+27-13
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ with this program; if not, write to the Free Software Foundation, Inc.,
2424
#include <cstdlib>
2525
#include <cstring>
2626
#include <cerrno>
27-
#include <unistd.h>
2827
#include <fstream>
2928
#include "log.h"
3029
#include "config.h"
@@ -38,6 +37,7 @@ namespace fs
3837
#define _WIN32_WINNT 0x0501
3938
#include <windows.h>
4039
#include <shlwapi.h>
40+
#include <io.h>
4141

4242
std::vector<DirListNode> GetDirListing(const std::string &pathstring)
4343
{
@@ -178,13 +178,27 @@ std::string TempPath()
178178
errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl;
179179
return "";
180180
}
181-
std::vector<char> buf(bufsize);
181+
std::string buf;
182+
buf.resize(bufsize);
182183
DWORD len = GetTempPath(bufsize, &buf[0]);
183184
if(len == 0 || len > bufsize){
184185
errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl;
185186
return "";
186187
}
187-
return std::string(buf.begin(), buf.begin() + len);
188+
buf.resize(len);
189+
return buf;
190+
}
191+
192+
std::string CreateTempFile()
193+
{
194+
std::string path = TempPath() + DIR_DELIM "MT_XXXXXX";
195+
_mktemp_s(&path[0], path.size() + 1); // modifies path
196+
HANDLE file = CreateFile(path.c_str(), GENERIC_WRITE, 0, nullptr,
197+
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
198+
if (file == INVALID_HANDLE_VALUE)
199+
return "";
200+
CloseHandle(file);
201+
return path;
188202
}
189203

190204
#else // POSIX
@@ -366,6 +380,16 @@ std::string TempPath()
366380
#endif
367381
}
368382

383+
std::string CreateTempFile()
384+
{
385+
std::string path = TempPath() + DIR_DELIM "MT_XXXXXX";
386+
int fd = mkstemp(&path[0]); // modifies path
387+
if (fd == -1)
388+
return "";
389+
close(fd);
390+
return path;
391+
}
392+
369393
#endif
370394

371395
void GetRecursiveDirs(std::vector<std::string> &dirs, const std::string &dir)
@@ -813,15 +837,5 @@ bool Rename(const std::string &from, const std::string &to)
813837
return rename(from.c_str(), to.c_str()) == 0;
814838
}
815839

816-
std::string CreateTempFile()
817-
{
818-
std::string path = TempPath() + DIR_DELIM "MT_XXXXXX";
819-
int fd = mkstemp(&path[0]); // modifies path
820-
if (fd == -1)
821-
return "";
822-
close(fd);
823-
return path;
824-
}
825-
826840
} // namespace fs
827841

0 commit comments

Comments
 (0)
Please sign in to comment.