blob: 2c6fb1c321688d50420020ddff06bdc3aaf309c0 [file] [log] [blame]
Elliott Hughesb4f76162013-09-19 16:27:24 -07001/*
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
Calin Juravlefe317a32014-02-21 15:11:03 +000019template<int (*mk_func)(char*)>
20class GenericTemporaryFile {
Elliott Hughesb4f76162013-09-19 16:27:24 -070021 public:
Calin Juravlefe317a32014-02-21 15:11:03 +000022 GenericTemporaryFile() {
Elliott Hughes925753a2013-10-18 13:17:18 -070023 // 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 }
Elliott Hughesb4f76162013-09-19 16:27:24 -070031 }
32
Calin Juravlefe317a32014-02-21 15:11:03 +000033 ~GenericTemporaryFile() {
Elliott Hughesb4f76162013-09-19 16:27:24 -070034 close(fd);
35 unlink(filename);
36 }
37
38 int fd;
39 char filename[1024];
Elliott Hughes925753a2013-10-18 13:17:18 -070040
41 private:
42 void init(const char* tmp_dir) {
43 snprintf(filename, sizeof(filename), "%s/TemporaryFile-XXXXXX", tmp_dir);
Calin Juravlefe317a32014-02-21 15:11:03 +000044 fd = mk_func(filename);
Elliott Hughes925753a2013-10-18 13:17:18 -070045 }
Elliott Hughesb4f76162013-09-19 16:27:24 -070046};
Calin Juravlefe317a32014-02-21 15:11:03 +000047
48typedef GenericTemporaryFile<mkstemp> TemporaryFile;