How to get the path to the current file (pwd) in Linux from C?

Simply opening and reading directories does not change the current working directory. However, changing directory in your program will.

for reference,

#include <unistd.h>
#include <stdio.h>

int main() {
    char cwd[1024];
    chdir("/path/to/change/directory/to");
    getcwd(cwd, sizeof(cwd));
    printf("Current working dir: %s\n", cwd);
}

For POSIX systems I found three solutions:

Get value from an environment variables "PWD"

#include <stdio.h>
#include <stdlib.h>

#ifdef __unix__
    #define IS_POSIX 1
#else
    #define IS_POSIX 0
#endif


int main (int argv, char **argc)
{
    if (IS_POSIX == 1) {
        puts("Path info by use environment variable PWD:");
        printf("\tWorkdir: %s\n", getenv("PWD"));
        printf("\tFilepath: %s/%s\n", getenv("PWD"), __FILE__);
    }
    return 0;
}

Result:

Path info by use environment variable PWD:
    Workdir: /media/setivolkylany/WorkDisk/Programming/Projects/c-utils
    Filepath: /media/setivolkylany/WorkDisk/Programming/Projects/c-utils/main.c

Use getcwd()

#include <stdio.h>
#include <stdlib.h>

#ifdef __unix__
    #define IS_POSIX 1
    #include <unistd.h>
#else
    #define IS_POSIX 0
#endif


int main (int argv, char **argc)
{
    if (IS_POSIX == 1) {
        char cwd[1024];
        getcwd(cwd, sizeof(cwd));
        puts("Path info by use getcwd():");
        printf("\tWorkdir: %s\n", cwd);
        printf("\tFilepath: %s/%s\n", cwd, __FILE__);
    }
    return 0;
}

Result

Path info by use getcwd():
    Workdir: /media/setivolkylany/WorkDisk/Programming/Projects/c-utils
    Filepath: /media/setivolkylany/WorkDisk/Programming/Projects/c-utils/main.c

Execute system command "pwd" and read output

#ifdef __unix__
    #define IS_POSIX 1
    #define _BSD_SOURCE
#else
    #define IS_POSIX 0
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main (int argv, char **argc)
{
    if (IS_POSIX == 1) {
        char buffer[500];
        FILE *output;

        // read output of a command
        output = popen("/bin/pwd", "r");
        char *pwd = fgets(buffer, sizeof(buffer), output);

        // strip '\n' on ending of a line
        pwd = strtok(pwd, "\n");

        puts("Path info by execute shell command 'pwd':");
        printf("\tWorkdir: %s\n", pwd);
        printf("\tFilepath: %s/%s\n", pwd, __FILE__);
    }
    return 0;
}

Result:

Path info by execute shell command 'pwd':
    Workdir: /media/setivolkylany/WorkDisk/Programming/Projects/c-utils
    Filepath: /media/setivolkylany/WorkDisk/Programming/Projects/c-utils/main.c

You can use chdir(2) to change dir from C, then system("pwd"); will give you what ever directory you chdir'ed to.

The C-equvivalent of the pwd-command is getcwd(3).

Tags:

Linux

C

Path