-
trouble using getcwd
Nothing gets printed out. I'm unclear as to what the difference is from the return value and the buffer reference?
Code:
char buffer[200];
char *startingPath = getcwd(buffer, sizeof(unsigned long));
cout << "Here is path: " << startingPath << endl;
I'm on Windows 7.
-
It didn't work because you (inexplicably!) passed sizeof(unsigned long) as the buffer size, which is either the number 4 or 8. Since that was presumably not enough to hold the directory name, it didn't work (i.e., it returned NULL to indicate this).
Code:
char buffer[200];
if (getcwd(buffer, sizeof(buffer)) == NULL) {
cerr << "getcwd failed\n";
exit(1);
}
cout << "Here is path: " << buffer << endl;
The return value is the same as buffer, unless buffer is NULL, in which case the function allocates a properly sized array for you.
Code:
char *buf = getcwd(NULL, 0);
// ... use buf
free(buf); // be sure to free it
getcwd(3): current working directory - Linux man page
-
I changed unsigned long to MAX_PATH but the macro is not found. I tried including limits.h but no luck. Which library is the MAX_PATH defined in?
-
-
I got it working, it was MAX_PATH in the windows.h library. Is there a more platform independent solution?
-
stdio only defines FILENAME_MAX for the file primitives.
Posix defines PATH_MAX and windows apparently defines MAX_PATH, as getcwd() is platform specific anyway, the associated limits are platform specific too.