85 lines
1.5 KiB
C++
Executable File
85 lines
1.5 KiB
C++
Executable File
#ifndef TEMPFILE_H_
|
|
#define TEMPFILE_H_
|
|
|
|
#include "lib/os/os.h"
|
|
|
|
#ifdef _WIN32
|
|
#include <io.h>
|
|
#define mkstemps
|
|
#else
|
|
#include <unistd.h>
|
|
#endif
|
|
#include "bts_assert.h"
|
|
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string>
|
|
#include <fstream>
|
|
#include <assert.h>
|
|
#include <sstream>
|
|
|
|
namespace bts {
|
|
namespace utils {
|
|
|
|
class TempFile
|
|
{
|
|
private:
|
|
std::string _name;
|
|
|
|
public:
|
|
TempFile() : _name()
|
|
{
|
|
std::string temp;
|
|
char* temp_cstr = getenv("TEMP");
|
|
if (temp_cstr != NULL) temp = temp_cstr;
|
|
bts::os::normalize_path(temp);
|
|
|
|
if (!bts::os::is_windows() && temp.empty())
|
|
temp = "/tmp";
|
|
temp += "/bts_tmp_XXXXXX";
|
|
|
|
char name_buf[1024] = {0};
|
|
bts::os::strncpy(name_buf, temp.c_str(), sizeof(name_buf));
|
|
|
|
#ifdef _WIN32
|
|
int result;
|
|
int count = 0;
|
|
FILE* fp;
|
|
do
|
|
{
|
|
count++;
|
|
bts_assert(count < 10);
|
|
result = _mktemp_s(name_buf, sizeof(name_buf));
|
|
bts_assert(!result);
|
|
result = fopen_s(&fp, name_buf, "w");
|
|
} while(result);
|
|
fclose(fp);
|
|
#else
|
|
int result = mkstemp(name_buf);
|
|
assert(result != -1);
|
|
close(result);
|
|
#endif
|
|
_name = name_buf;
|
|
}
|
|
|
|
std::shared_ptr<std::ofstream> out()
|
|
{
|
|
std::shared_ptr<std::ofstream> o(new std::ofstream(_name.c_str (), std::ios::out));
|
|
assert(!o->fail());
|
|
return o;
|
|
}
|
|
|
|
const std::string& path()
|
|
{
|
|
return _name;
|
|
}
|
|
|
|
~TempFile()
|
|
{
|
|
std::remove(_name.c_str());
|
|
}
|
|
};
|
|
}}
|
|
#endif
|
|
|