]> git.lyx.org Git - lyx.git/blob - src/support/tempname.C
fix parse error in FormPreferences, make LyX be able to compile with gcc 2.97, use...
[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 static inline
16 int make_tempfile(char * templ) 
17 {
18 #ifdef HAVE_MKSTEMP
19         return ::mkstemp(templ);
20 #else
21 #ifdef HAVE_MKTEMP
22         // This probably just barely works...
23         ::mktemp(templ);
24         return ::open(templ, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
25 #else
26 #warning FIX FIX FIX
27 #endif
28 #endif
29 }
30         
31 string const lyx::tempName(string const & dir, string const & mask)
32 {
33         string const tmpdir(dir.empty() ? system_tempdir : dir);
34         string tmpfl(AddName(tmpdir, mask));
35         tmpfl += tostr(getpid());
36         tmpfl += "XXXXXX";
37
38         // The supposedly safe mkstemp version
39         char * tmpl = new char[tmpfl.length() + 1]; // + 1 for '\0'
40         tmpfl.copy(tmpl, string::npos);
41         tmpl[tmpfl.length()] = '\0'; // terminator
42         
43         int const tmpf = make_tempfile(tmpl);
44         if (tmpf != -1) {
45                 string const t(tmpl);
46                 ::close(tmpf);
47                 delete [] tmpl;
48                 lyxerr[Debug::FILES] << "Temporary file `" << t
49                                      << "' created." << endl;
50                 return t;
51         } else {
52                 lyxerr[Debug::FILES]
53                         << "LyX Error: Unable to create temporary file."
54                         << endl;
55                 delete [] tmpl;
56                 return string();
57         }
58 }