]> git.lyx.org Git - lyx.git/blob - src/support/tempname.C
use anon namespace, somewhat better comp. handling of minipages, not quite there yet
[lyx.git] / src / support / tempname.C
1 #include <config.h>
2
3 #include <cstdlib>
4 #include <unistd.h>
5
6 #include "LString.h"
7 #include "support/lyxlib.h"
8 #include "support/filetools.h"
9 #include "debug.h"
10
11 using std::endl;
12
13 extern string system_tempdir;
14
15 namespace {
16
17 inline
18 int make_tempfile(char * templ) 
19 {
20 #ifdef HAVE_MKSTEMP
21         return ::mkstemp(templ);
22 #else
23 #ifdef HAVE_MKTEMP
24         // This probably just barely works...
25         ::mktemp(templ);
26         return ::open(templ, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
27 #else
28 #warning FIX FIX FIX
29 #endif
30 #endif
31 }
32
33 } // namespace anon
34
35
36 string const lyx::tempName(string const & dir, string const & mask)
37 {
38         string const tmpdir(dir.empty() ? system_tempdir : dir);
39         string tmpfl(AddName(tmpdir, mask));
40         tmpfl += tostr(getpid());
41         tmpfl += "XXXXXX";
42
43         // The supposedly safe mkstemp version
44         char * tmpl = new char[tmpfl.length() + 1]; // + 1 for '\0'
45         tmpfl.copy(tmpl, string::npos);
46         tmpl[tmpfl.length()] = '\0'; // terminator
47         
48         int const tmpf = make_tempfile(tmpl);
49         if (tmpf != -1) {
50                 string const t(tmpl);
51                 ::close(tmpf);
52                 delete [] tmpl;
53                 lyxerr[Debug::FILES] << "Temporary file `" << t
54                                      << "' created." << endl;
55                 return t;
56         } else {
57                 lyxerr[Debug::FILES]
58                         << "LyX Error: Unable to create temporary file."
59                         << endl;
60                 delete [] tmpl;
61                 return string();
62         }
63 }