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