Fix tg_termpos1 for 64-bit termpos
[xapian.git] / xapian-applications / omega / tmpdir.cc
blobd71d8f6e661f0cc092bbaacb3ac91ed0f7388370
1 /** @file
2 * @brief create a temporary directory securely
3 */
4 /* Copyright (C) 2007,2011,2016 Olly Betts
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 #include <config.h>
23 #include "tmpdir.h"
25 #include "safesysstat.h"
26 #include "safeunistd.h"
27 #include <sys/types.h>
28 #include <stdlib.h> // Not cstdlib as we want mkdtemp.
29 #include <cstring>
30 #include <string>
32 #ifndef HAVE_MKDTEMP
33 #include "portability/mkdtemp.h"
34 #endif
36 #include "stringutils.h"
38 using namespace std;
40 static string tmpdir;
42 #define TMPDIR_LEAF "/omindex-XXXXXX"
44 const string &
45 get_tmpdir()
47 if (tmpdir.empty()) {
48 const char * p = getenv("TMPDIR");
49 if (!p) p = "/tmp";
50 size_t plen = strlen(p);
51 size_t leaflen = CONST_STRLEN(TMPDIR_LEAF);
52 char * dir_template = new char[plen + leaflen + 1];
53 memcpy(dir_template, p, plen);
54 memcpy(dir_template + plen, TMPDIR_LEAF, leaflen + 1);
55 p = mkdtemp(dir_template);
56 if (p) {
57 dir_template[plen + leaflen] = '/';
58 tmpdir.assign(dir_template, plen + leaflen + 1);
60 delete [] dir_template;
62 return tmpdir;
65 void
66 remove_tmpdir()
68 if (!tmpdir.empty())
69 rmdir(tmpdir.c_str());