We used `getcwd()` with `PATH_MAX` to get the current directory.
However, `PATH_MAX` does not exist in environments such as GNU Hurd.
Debian developers avoided `PATH_MAX`
by using `get_current_dir_name()` instead of `getcwd()`.
It needed to protected with `#ifdef _GNU_SOURCE`
since `get_current_dir_name()` is glibc specific.
So `PATH_MAX` was still required in non-glibc environments.
There is a `getcwd()` extention that can avoid `PATH_MAX`
by setting the first argument to NULL.
The extension can be used in many environments, including glibc,
but POSIX does not recommend it in conforming applications.
This commit improves portability
by obtaining the current directory
with a method conforming to the standard.
string
get_working_directory ()
{
-#ifdef _GNU_SOURCE
- char *cwd = get_current_dir_name();
- string scwd(cwd);
- free(cwd);
- return scwd;
+#ifdef PATH_MAX
+ vector<char> cwd (PATH_MAX);
#else
- char cwd[PATH_MAX];
- // getcwd returns NULL upon a failure, contents of cwd would be undefined!
- return string (getcwd (cwd, PATH_MAX));
+ vector<char> cwd (1024);
#endif
+ while (getcwd (cwd.data (), cwd.size ()) == NULL)
+ {
+ if (errno != ERANGE)
+ {
+ // getcwd () fails.
+ return "";
+ }
+ cwd.resize (cwd.size () * 2);
+ }
+ return string (cwd.data ());
}
/* Join components to full file_name. */