xlnt/tests/helpers/temporary_file.hpp

55 lines
1.1 KiB
C++
Raw Normal View History

2014-05-12 19:59:33 -04:00
#pragma once
#include <array>
#include <cstdio>
#include <string>
2015-11-01 09:47:52 -05:00
#include <detail/include_windows.hpp>
#include <helpers/path_helper.hpp>
2014-05-19 20:47:15 -04:00
2014-05-12 19:59:33 -04:00
class TemporaryFile
{
public:
2015-11-10 19:46:57 -05:00
static std::string CreateTemporaryFilename()
2014-05-12 19:59:33 -04:00
{
#ifdef _MSC_VER
2014-05-14 22:07:23 -04:00
std::array<TCHAR, MAX_PATH> buffer;
DWORD result = GetTempPath(static_cast<DWORD>(buffer.size()), buffer.data());
2014-05-14 22:07:23 -04:00
if(result > MAX_PATH)
{
throw std::runtime_error("buffer is too small");
}
2014-05-15 17:12:09 -04:00
if(result == 0)
2014-05-14 22:07:23 -04:00
{
throw std::runtime_error("GetTempPath failed");
}
2015-11-10 19:46:57 -05:00
std::string directory(buffer.begin(), buffer.begin() + result);
2014-05-19 20:47:15 -04:00
return PathHelper::WindowsToUniversalPath(directory + "xlnt.xlsx");
2014-05-14 22:07:23 -04:00
#else
2014-06-13 11:41:32 -04:00
return "/tmp/xlnt.xlsx";
2014-05-14 22:07:23 -04:00
#endif
}
2014-05-12 19:59:33 -04:00
TemporaryFile() : filename_(CreateTemporaryFilename())
{
if(PathHelper::FileExists(GetFilename()))
{
2015-11-10 19:46:57 -05:00
std::remove(filename_.c_str());
}
2014-05-12 19:59:33 -04:00
}
~TemporaryFile()
{
2015-11-10 19:46:57 -05:00
std::remove(filename_.c_str());
2014-05-12 19:59:33 -04:00
}
2015-11-10 19:46:57 -05:00
std::string GetFilename() const { return filename_; }
2014-05-12 19:59:33 -04:00
private:
2015-11-10 19:46:57 -05:00
const std::string filename_;
2014-05-14 22:07:23 -04:00
};