Open Model Railroad Network (OpenMRN)
Loading...
Searching...
No Matches
TempFile.hxx
Go to the documentation of this file.
1
36#ifndef _OS_TEMPFILE_HXX_
37#define _OS_TEMPFILE_HXX_
38
39#include <string>
40
41#include <fcntl.h>
42#include <stdlib.h>
43#include <unistd.h>
44#include "utils/logging.h"
45
52class TempDir {
53public:
54#ifndef __FreeRTOS__
55 TempDir();
56#endif
57
58 ~TempDir() {
59 if (::rmdir(dirName_.c_str()) != 0)
60 {
61 LOG(WARNING, "Error deleting temporary directory %s: %s",
62 dirName_.c_str(), strerror(errno));
63 }
64 }
65
67 static TempDir* instance() {
68 static TempDir me;
69 return &me;
70 }
71
73 const string& name() const {
74 return dirName_;
75 }
76
77private:
79 string dirName_;
80};
81
84class TempFile {
85public:
90 TempFile(const TempDir& dir, const string& basename);
91
92 ~TempFile() {
93 ::close(fd_);
94 ::unlink(fileName_.c_str());
95 }
96
98 const string& name() const {
99 return fileName_;
100 }
101
103 int fd()
104 {
105 return fd_;
106 }
107
110 void write(const uint8_t byte) {
111 string s;
112 s.push_back(byte);
113 write(s);
114 }
115
118 void rewrite(const string& s);
119
122 void write(const string& s) {
123 size_t ofs = 0;
124 while (ofs < s.size()) {
125 int ret = ::write(fd_, s.data() + ofs, s.size() - ofs);
126 HASSERT(ret >= 0);
127 ofs += ret;
128 }
129#ifndef __WINNT__
130 fsync(fd_);
131#endif
132 }
133
134private:
136 string fileName_;
138 int fd_;
139};
140
141#endif
This class creates a temporary directory for the test, and removes it when the test is done.
Definition TempFile.hxx:52
const string & name() const
Definition TempFile.hxx:73
string dirName_
name of the temporary directory.
Definition TempFile.hxx:79
static TempDir * instance()
Definition TempFile.hxx:67
This class creates a temporary file for the test, and removes it when the test is done.
Definition TempFile.hxx:84
string fileName_
The full path name.
Definition TempFile.hxx:136
int fd_
The file descriptor.
Definition TempFile.hxx:138
void rewrite(const string &s)
writes the given data to the temporary file from offset 0.
Definition TempFile.cxx:79
int fd()
Definition TempFile.hxx:103
void write(const uint8_t byte)
writes a single byte to the temporary file.
Definition TempFile.hxx:110
void write(const string &s)
writes the given data to the temporary file.
Definition TempFile.hxx:122
const string & name() const
Definition TempFile.hxx:98
#define LOG(level, message...)
Conditionally write a message to the logging output.
Definition logging.h:99
static const int WARNING
Loglevel that is always printed, reporting a warning or a retryable error.
Definition logging.h:55
#define HASSERT(x)
Checks that the value of expression x is true, else terminates the current process.
Definition macros.h:138