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