The getcwd() function places an absolute pathname of the current working directory in the array pointed to by buf, and returns buf. The size argument is the size in bytes of the character array pointed to by the buf argument.
On Windows, you need to use the equivalent functionality provided by the Windows API, ie GetCurrentDirectory() , declared in windows. h .
Have you had a look at getcwd()
?
#include <unistd.h>
char *getcwd(char *buf, size_t size);
Simple example:
#include <unistd.h>
#include <stdio.h>
#include <limits.h>
int main() {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("Current working dir: %s\n", cwd);
} else {
perror("getcwd() error");
return 1;
}
return 0;
}
Look up the man page for getcwd
.
Although the question is tagged Unix, people also get to visit it when their target platform is Windows, and the answer for Windows is the GetCurrentDirectory()
function:
DWORD WINAPI GetCurrentDirectory(
_In_ DWORD nBufferLength,
_Out_ LPTSTR lpBuffer
);
These answers apply to both C and C++ code.
Link suggested by user4581301 in a comment to another question, and verified as the current top choice with a Google search 'site:microsoft.com getcurrentdirectory'.
#include <stdio.h> /* defines FILENAME_MAX */
//#define WINDOWS /* uncomment this line to use it for windows.*/
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
int main(){
char buff[FILENAME_MAX];
GetCurrentDir( buff, FILENAME_MAX );
printf("Current working dir: %s\n", buff);
return 1;
}
Note that getcwd(3)
is also available in Microsoft's libc: getcwd(3), and works the same way you'd expect.
Must link with -loldnames
(oldnames.lib, which is done automatically in most cases), or use _getcwd()
. The unprefixed version is unavailable under Windows RT.
To get current directory (where you execute your target program), you can use the following example code, which works for both Visual Studio and Linux/MacOS(gcc/clang), both C and C++:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(_MSC_VER)
#include <direct.h>
#define getcwd _getcwd
#elif defined(__GNUC__)
#include <unistd.h>
#endif
int main() {
char* buffer;
if( (buffer=getcwd(NULL, 0)) == NULL) {
perror("failed to get current directory\n");
} else {
printf("%s \nLength: %zu\n", buffer, strlen(buffer));
free(buffer);
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With