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