]> git.lyx.org Git - lyx.git/blob - src/support/tempname.C
Guard HAVE_UNISTD_H.
[lyx.git] / src / support / tempname.C
1 /**
2  * \file tempname.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "support/lyxlib.h"
14
15 #include "support/convert.h"
16 #include "support/filetools.h"
17 #include "support/package.h"
18
19 #include "debug.h"
20
21 #include <boost/scoped_array.hpp>
22
23 #include <cstdlib>
24 #ifdef HAVE_UNISTD_H
25 # include <unistd.h>
26 #endif
27
28 #if !defined(HAVE_MKSTEMP) && defined(HAVE_MKTEMP)
29 # include <fcntl.h>
30 # include <sys/stat.h>
31 #endif
32
33 using boost::scoped_array;
34
35 using std::string;
36 using std::endl;
37
38 namespace {
39
40 inline
41 int make_tempfile(char * templ)
42 {
43 #if defined(HAVE_MKSTEMP)
44         return ::mkstemp(templ);
45 #elif defined(HAVE_MKTEMP)
46         // This probably just barely works...
47         ::mktemp(templ);
48         return ::open(templ, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
49 #else
50 #error FIX FIX FIX
51 #endif
52 }
53
54 } // namespace anon
55
56
57 string const lyx::support::tempName(string const & dir, string const & mask)
58 {
59         string const tmpdir(dir.empty() ? package().temp_dir() : dir);
60         string tmpfl(AddName(tmpdir, mask));
61         tmpfl += convert<string>(getpid());
62         tmpfl += "XXXXXX";
63
64         // The supposedly safe mkstemp version
65         scoped_array<char> tmpl(new char[tmpfl.length() + 1]); // + 1 for '\0'
66         tmpfl.copy(tmpl.get(), string::npos);
67         tmpl[tmpfl.length()] = '\0'; // terminator
68
69         int const tmpf = make_tempfile(tmpl.get());
70         if (tmpf != -1) {
71                 string const t(tmpl.get());
72                 ::close(tmpf);
73                 lyxerr[Debug::FILES] << "Temporary file `" << t
74                                      << "' created." << endl;
75                 return t;
76         } else {
77                 lyxerr[Debug::FILES]
78                         << "LyX Error: Unable to create temporary file."
79                         << endl;
80                 return string();
81         }
82 }