]> git.lyx.org Git - lyx.git/blob - src/support/getcwd.C
Don't use a global variable for avoiding removal of the system temp dir
[lyx.git] / src / support / getcwd.C
1 /**
2  * \file getcwd.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 #include "support/os.h"
15
16 #include <boost/scoped_array.hpp>
17
18 #include <cerrno>
19
20
21 namespace lyx {
22 #ifdef HAVE_UNISTD_H
23 # include <unistd.h>
24 #endif
25
26 #ifdef _WIN32
27 # include <windows.h>
28 #endif
29
30 using boost::scoped_array;
31 using support::os::internal_path;
32
33 using std::string;
34
35
36 namespace {
37
38 inline
39 char * l_getcwd(char * buffer, size_t size)
40 {
41 #ifdef _WIN32
42         GetCurrentDirectory(size, buffer);
43         return buffer;
44 #else
45         return ::getcwd(buffer, size);
46 #endif
47 }
48
49 } // namespace anon
50
51
52 // Returns current working directory
53 string const lyx::support::getcwd()
54 {
55         int n = 256;    // Assume path is less than 256 chars
56         char * err;
57         scoped_array<char> tbuf(new char[n]);
58
59         // Safe. Hopefully all getcwds behave this way!
60         while (((err = l_getcwd(tbuf.get(), n)) == 0) && (errno == ERANGE)) {
61                 // Buffer too small, double the buffersize and try again
62                 n *= 2;
63                 tbuf.reset(new char[n]);
64         }
65
66         string result;
67         if (err)
68                 result = tbuf.get();
69         return internal_path(result);
70 }
71
72
73 } // namespace lyx