TemporaryFile.h revision eda26bc1ffc60dc722a375095b9de4fd86959a1d
1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <fcntl.h>
18#include <unistd.h>
19
20template<int (*mk_fn)(char*)>
21class GenericTemporaryFile {
22 public:
23  GenericTemporaryFile(const char* dirpath = NULL) {
24    if (dirpath != NULL) {
25      init(dirpath);
26    } else {
27      // Since we might be running on the host or the target, and if we're
28      // running on the host we might be running under bionic or glibc,
29      // let's just try both possible temporary directories and take the
30      // first one that works.
31      init("/data/local/tmp");
32      if (fd == -1) {
33        init("/tmp");
34      }
35    }
36  }
37
38  ~GenericTemporaryFile() {
39    close(fd);
40    unlink(filename);
41  }
42
43  void reopen() {
44    close(fd);
45    fd = open(filename, O_RDWR);
46  }
47
48  int fd;
49  char filename[1024];
50
51 private:
52  void init(const char* tmp_dir) {
53    snprintf(filename, sizeof(filename), "%s/TemporaryFile-XXXXXX", tmp_dir);
54    fd = mk_fn(filename);
55  }
56};
57
58typedef GenericTemporaryFile<mkstemp> TemporaryFile;
59
60class TemporaryDir {
61 public:
62  TemporaryDir() {
63    if (!init("/data/local/tmp")) {
64      init("/tmp");
65    }
66  }
67
68  ~TemporaryDir() {
69    rmdir(dirname);
70  }
71
72  char dirname[1024];
73
74 private:
75  bool init(const char* tmp_dir) {
76    snprintf(dirname, sizeof(dirname), "%s/TemporaryDir-XXXXXX", tmp_dir);
77    return (mkdtemp(dirname) != NULL);
78  }
79
80};
81