]> git.lyx.org Git - lyx.git/blob - src/support/tempname.C
Consistent use of preprocessor guards;
[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 # ifdef HAVE_SYS_STAT_H
31 #  include <sys/stat.h>
32 # endif
33 #endif
34
35 using boost::scoped_array;
36
37 using std::string;
38 using std::endl;
39
40 namespace {
41
42 inline
43 int make_tempfile(char * templ)
44 {
45 #if defined(HAVE_MKSTEMP)
46         return ::mkstemp(templ);
47 #elif defined(HAVE_MKTEMP)
48         // This probably just barely works...
49         ::mktemp(templ);
50         return ::open(templ, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
51 #else
52 #error FIX FIX FIX
53 #endif
54 }
55
56 } // namespace anon
57
58
59 string const lyx::support::tempName(string const & dir, string const & mask)
60 {
61         string const tmpdir(dir.empty() ? package().temp_dir() : dir);
62         string tmpfl(AddName(tmpdir, mask));
63         tmpfl += convert<string>(getpid());
64         tmpfl += "XXXXXX";
65
66         // The supposedly safe mkstemp version
67         scoped_array<char> tmpl(new char[tmpfl.length() + 1]); // + 1 for '\0'
68         tmpfl.copy(tmpl.get(), string::npos);
69         tmpl[tmpfl.length()] = '\0'; // terminator
70
71         int const tmpf = make_tempfile(tmpl.get());
72         if (tmpf != -1) {
73                 string const t(tmpl.get());
74                 ::close(tmpf);
75                 lyxerr[Debug::FILES] << "Temporary file `" << t
76                                      << "' created." << endl;
77                 return t;
78         } else {
79                 lyxerr[Debug::FILES]
80                         << "LyX Error: Unable to create temporary file."
81                         << endl;
82                 return string();
83         }
84 }