Welcome to mirror list, hosted at ThFree Co, Russian Federation.

tempfile.hh « util - github.com/moses-smt/mosesdecoder.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 228238823df462f1814057b6c0662ee77d7c6805 (plain)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#ifndef UTIL_TEMPFILE_H
#define UTIL_TEMPFILE_H

// Utilities for creating temporary files and directories.

#include <cstdio>
#include <cstdlib>
#include <string>

#include <boost/filesystem.hpp>
#include <boost/noncopyable.hpp>

#include "util/exception.hh"

namespace util
{

/** Temporary directory.
 *
 * Automatically creates, and on destruction deletes, a temporary directory.
 * The actual directory in the filesystem will only exist while the temp_dir
 * object exists.
 *
 * If the directory no longer exists by the time the temp_dir is destroyed,
 * no cleanup happens.
 */
class temp_dir : boost::noncopyable
{
public:
  temp_dir()
  {
    char buf[] = "tmpdir.XXXXXX";
    m_path = std::string(mkdtemp(buf));
  }

  ~temp_dir()
  {
    boost::filesystem::remove_all(path());
  }

  /// Return the temporary directory's full path.
  const std::string &path() const { return m_path; }

private:
  std::string m_path;
};


/** Temporary file.
 *
 * Automatically creates, and on destruction deletes, a temporary file.
 */
class temp_file : boost::noncopyable
{
public:
  temp_file()
  {
    char buf[] = "tmp.XXXXXX";
    const int fd = mkstemp(buf);
    if (fd == -1) throw ErrnoException();
    close(fd);
    m_path = buf;
  }

  ~temp_file()
  {
    boost::filesystem::remove(path());
  }

  /// Return the temporary file's full path.
  const std::string &path() const { return m_path; }

private:
  std::string m_path;
};

} // namespace util

#endif