A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
Your program's working directory determines where relative paths resolve. If you open "data.txt" and the working directory is C:\Users\alex\projects, the file is looked up there. _getcwd (or getcwd on POSIX) writes the absolute path of the current working directory into a buffer you provide. If the buffer is too small, it returns NULL and sets errno to ERANGE.
#include <stdio.h>#ifdef _WIN32#include <direct.h>#define get_cwd _getcwd#else#include <unistd.h>#define get_cwd getcwd#endifint main(void) {char buffer[256];if (get_cwd(buffer, sizeof(buffer)) != NULL) {printf("Current directory: %s\n", buffer);} else {perror("getcwd");}return 0;}
The buffer size must be large enough for the full path plus the null terminator. PATH_MAX (typically 4096 on Linux, 260 on Windows) is the theoretical maximum. In practice, 256 covers most development scenarios, but production code should use PATH_MAX or dynamically allocate. Passing NULL as the buffer with a size of 0 triggers implementation-defined behavior on some systems, so avoid that pattern.
Knowing your working directory matters for debugging file-not-found errors, for constructing absolute paths in log messages, and for validating that your program was launched from the expected location. Next: _chdir, for changing the working directory programmatically.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.