]> git.lyx.org Git - lyx.git/blob - src/support/tempname.C
Fix the texinfo dialog and associated cleanup.
[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 <cstdlib>
14 #include <unistd.h>
15
16 #include "LString.h"
17 #include "support/lyxlib.h"
18 #include "support/filetools.h"
19 #include "support/tostr.h"
20 #include "debug.h"
21 #include "os.h"
22
23 using std::endl;
24
25
26 namespace {
27
28 inline
29 int make_tempfile(char * templ)
30 {
31 #if defined(HAVE_MKSTEMP)
32         return ::mkstemp(templ);
33 #elif defined(HAVE_MKTEMP)
34         // This probably just barely works...
35         ::mktemp(templ);
36         return ::open(templ, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
37 #else
38 #error FIX FIX FIX
39 #endif
40 }
41
42 } // namespace anon
43
44
45 string const lyx::tempName(string const & dir, string const & mask)
46 {
47         string const tmpdir(dir.empty() ? os::getTmpDir() : dir);
48         string tmpfl(AddName(tmpdir, mask));
49         tmpfl += tostr(getpid());
50         tmpfl += "XXXXXX";
51
52         // The supposedly safe mkstemp version
53         char * tmpl = new char[tmpfl.length() + 1]; // + 1 for '\0'
54         tmpfl.copy(tmpl, string::npos);
55         tmpl[tmpfl.length()] = '\0'; // terminator
56
57         int const tmpf = make_tempfile(tmpl);
58         if (tmpf != -1) {
59                 string const t(tmpl);
60                 ::close(tmpf);
61                 delete [] tmpl;
62                 lyxerr[Debug::FILES] << "Temporary file `" << t
63                                      << "' created." << endl;
64                 return t;
65         } else {
66                 lyxerr[Debug::FILES]
67                         << "LyX Error: Unable to create temporary file."
68                         << endl;
69                 delete [] tmpl;
70                 return string();
71         }
72 }