I\'d like to know if it is somehow possible to run system("pwd")
on the current DIR. So for example let\'s have this folder structure:
exam
How to not hardcode the path length with pathconf
I believe this is the correct way to do it:
#define _XOPEN_SOURCE 700
#include
#include
#include
#include
int main(void) {
long n;
char *buf;
n = pathconf(".", _PC_PATH_MAX);
assert(n != -1);
buf = malloc(n * sizeof(*buf));
assert(buf);
if (getcwd(buf, n) == NULL) {
perror("getcwd");
exit(EXIT_FAILURE);
} else {
printf("%s\n", buf);
}
free(buf);
return EXIT_SUCCESS;
}
GitHub upstream.
Compile and run:
gcc -Wall -Wextra -std=c11 -pedantic-errors -o getcwd.out getcwd.c
./getcwd.out
POSIX describes _PC_PATH_MAX it as:
The value returned for the variable {PATH_MAX} indicates the longest relative pathname that could be given if the specified directory is the process' current working directory. A process may not always be able to generate a name that long and use it if a subdirectory in the pathname crosses into a more restrictive file system.
Tested on Ubuntu 18.10, n == 4096
in this implementation.