xlnt/tests/helpers/temporary_file.hpp

55 lines
1.0 KiB
C++
Raw Normal View History

2014-05-13 07:59:33 +08:00
#pragma once
#include <array>
#include <cstdio>
#include <string>
2014-05-16 05:12:09 +08:00
#ifdef _WIN32
2014-05-22 05:48:51 +08:00
#define NOMINMAX
2014-05-16 05:12:09 +08:00
#include <Windows.h>
#endif
2014-06-06 04:19:31 +08:00
#include "path_helper.hpp"
2014-05-20 08:47:15 +08:00
2014-05-13 07:59:33 +08:00
class TemporaryFile
{
public:
static std::string CreateTemporaryFilename()
{
2014-05-15 10:07:23 +08:00
#ifdef _WIN32
std::array<TCHAR, MAX_PATH> buffer;
DWORD result = GetTempPath(static_cast<DWORD>(buffer.size()), buffer.data());
if(result > MAX_PATH)
{
throw std::runtime_error("buffer is too small");
}
2014-05-16 05:12:09 +08:00
if(result == 0)
2014-05-15 10:07:23 +08:00
{
throw std::runtime_error("GetTempPath failed");
}
std::string directory(buffer.begin(), buffer.begin() + result);
2014-05-20 08:47:15 +08:00
return PathHelper::WindowsToUniversalPath(directory + "xlnt.xlsx");
2014-05-15 10:07:23 +08:00
#else
2014-06-13 23:41:32 +08:00
return "/tmp/xlnt.xlsx";
2014-05-15 10:07:23 +08:00
#endif
}
2014-05-13 07:59:33 +08:00
TemporaryFile() : filename_(CreateTemporaryFilename())
{
if(PathHelper::FileExists(GetFilename()))
{
std::remove(filename_.c_str());
}
2014-05-13 07:59:33 +08:00
}
~TemporaryFile()
{
std::remove(filename_.c_str());
2014-05-13 07:59:33 +08:00
}
std::string GetFilename() const { return filename_; }
private:
const std::string filename_;
2014-05-15 10:07:23 +08:00
};