In system programming, applications sometimes need to determine the directory from which the current process is operating. The current working directory can be useful when handling relative file paths, locating application resources, creating files, or displaying the process environment.
The C standard library does not provide a single portable function for retrieving the current working directory on every operating system. Platform-specific APIs are therefore required. Windows provides GetCurrentDirectoryA, while Unix-like systems such as Linux commonly use the POSIX getcwd function.
A portable implementation can hide these operating system differences behind one helper function:
#include <stdio.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
int get_current_dir(char *path, const size_t size) {
#ifdef _WIN32
const DWORD len = GetCurrentDirectoryA((DWORD) size, path);
if (len == 0 || len >= size) {
return 1;
}
#else
if (!getcwd(path, size)) {
return 1;
}
#endif
return 0;
}
int main(void) {
char path[4096];
if (get_current_dir(path, sizeof(path))) {
printf("Unable to get current working directory\n");
return 1;
}
printf("%s\n", path);
return 0;
}
On Windows, GetCurrentDirectoryA writes the current directory path into the supplied buffer. Its return value which indicates the length of the resulting path, allowing the code to detect both API failures and cases where the provided buffer is not large enough.
On Linux and other Unix-like platforms, getcwd fills the specified character buffer with the current working directory.
Leave a Comment
Cancel reply