Skip to content

Commit 964a85c

Browse files
committed
Make get_current_working_directory return the canonical path name
Symlinks should be expanded to avoid ambiguity. The reimplementation also avoids realloc-loops.
1 parent f5073df commit 964a85c

File tree

1 file changed

+16
-16
lines changed

1 file changed

+16
-16
lines changed

src/util/file_util.cpp

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,10 @@ Date: January 2012
1313

1414
#include "file_util.h"
1515

16+
#include "invariant.h"
17+
1618
#include <cerrno>
19+
#include <cstring>
1720

1821
#if defined(__linux__) || \
1922
defined(__FreeBSD_kernel__) || \
@@ -36,29 +39,26 @@ Date: January 2012
3639
#define chdir _chdir
3740
#define popen _popen
3841
#define pclose _pclose
39-
#else
40-
#include <cstring>
4142
#endif
4243

4344
/// \return current working directory
4445
std::string get_current_working_directory()
4546
{
46-
unsigned bsize=50;
47-
48-
char *buf=reinterpret_cast<char*>(malloc(sizeof(char)*bsize));
49-
if(!buf)
50-
abort();
51-
47+
#ifndef _WIN32
5248
errno=0;
49+
char *wd=realpath(".", nullptr);
50+
INVARIANT(
51+
wd!=nullptr && errno==0,
52+
std::string("realpath failed: ")+strerror(errno));
5353

54-
while(buf && getcwd(buf, bsize-1)==nullptr && errno==ERANGE)
55-
{
56-
bsize*=2;
57-
buf=reinterpret_cast<char*>(realloc(buf, sizeof(char)*bsize));
58-
}
59-
60-
std::string working_directory=buf;
61-
free(buf);
54+
std::string working_directory=wd;
55+
free(wd);
56+
#else
57+
char buffer[4096];
58+
DWORD retval=GetCurrentDirectory(4096, buffer);
59+
CHECK_RETURN(retval>0);
60+
std::string working_directory(buffer);
61+
#endif
6262

6363
return working_directory;
6464
}

0 commit comments

Comments
 (0)