TemporaryFile.h revision d4934a70e69365c97b1378820152e134a0089b5e
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 <unistd.h>
18
19template<int (*mk_fn)(char*)>
20class GenericTemporaryFile {
21 public:
22  GenericTemporaryFile(const char* dirpath = NULL) {
23    if (dirpath != NULL) {
24      init(dirpath);
25    } else {
26      // Since we might be running on the host or the target, and if we're
27      // running on the host we might be running under bionic or glibc,
28      // let's just try both possible temporary directories and take the
29      // first one that works.
30      init("/data/local/tmp");
31      if (fd == -1) {
32        init("/tmp");
33      }
34    }
35  }
36
37  ~GenericTemporaryFile() {
38    close(fd);
39    unlink(filename);
40  }
41
42  int fd;
43  char filename[1024];
44
45 private:
46  void init(const char* tmp_dir) {
47    snprintf(filename, sizeof(filename), "%s/TemporaryFile-XXXXXX", tmp_dir);
48    fd = mk_fn(filename);
49  }
50};
51
52typedef GenericTemporaryFile<mkstemp> TemporaryFile;
53
54class TemporaryDir {
55 public:
56  TemporaryDir() {
57    if (!init("/data/local/tmp")) {
58      init("/tmp");
59    }
60  }
61
62  ~TemporaryDir() {
63    rmdir(dirname);
64  }
65
66  char dirname[1024];
67
68 private:
69  bool init(const char* tmp_dir) {
70    snprintf(dirname, sizeof(dirname), "%s/TemporaryDir-XXXXXX", tmp_dir);
71    return (mkdtemp(dirname) != NULL);
72  }
73
74};
75