TemporaryFile.h revision fe317a3775e16d466bb884a8e054fd77f7087bb3
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_func)(char*)>
20class GenericTemporaryFile {
21 public:
22  GenericTemporaryFile() {
23    // Since we might be running on the host or the target, and if we're
24    // running on the host we might be running under bionic or glibc,
25    // let's just try both possible temporary directories and take the
26    // first one that works.
27    init("/data/local/tmp");
28    if (fd == -1) {
29      init("/tmp");
30    }
31  }
32
33  ~GenericTemporaryFile() {
34    close(fd);
35    unlink(filename);
36  }
37
38  int fd;
39  char filename[1024];
40
41 private:
42  void init(const char* tmp_dir) {
43    snprintf(filename, sizeof(filename), "%s/TemporaryFile-XXXXXX", tmp_dir);
44    fd = mk_func(filename);
45  }
46};
47
48typedef GenericTemporaryFile<mkstemp> TemporaryFile;
49