conffiletemp.cpp
1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "conffiletemp.h"
#include <vector>
#include "unistd.h"
#include <stdexcept>
ConfFileTemp::ConfFileTemp()
{
const std::string templateName("/tmp/flashmqconf_XXXXXX");
std::vector<char> nameBuf(templateName.size() + 1, 0);
std::copy(templateName.begin(), templateName.end(), nameBuf.begin());
this->fd = mkstemp(nameBuf.data());
if (this->fd < 0)
{
throw std::runtime_error("mkstemp error.");
}
this->filePath = nameBuf.data();
}
ConfFileTemp::~ConfFileTemp()
{
closeFile();
if (!this->filePath.empty())
unlink(this->filePath.c_str());
}
const std::string &ConfFileTemp::getFilePath() const
{
if (fd > 0)
throw std::runtime_error("You first need to close the file before using it.");
return this->filePath;
}
void ConfFileTemp::writeLine(const std::string &line)
{
write(this->fd, line.c_str(), line.size());
write(this->fd, "\n", 1);
}
void ConfFileTemp::closeFile()
{
if (this->fd < 0)
return;
close(this->fd);
this->fd = -1;
}