C program in Linux to find the current working directory (PWD)

getcwd, getwd, get_current_dir_name functions return a null-terminated string containing an absolute pathname that is the current working directory of the calling process. The pathname is returned as the function result and via the argument buf, if present.

 $ vim getpwd.c 
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int atgc, char **argv) {
        char *run_dir = (char *) malloc (1024);
        if (getcwd(run_dir, 1024) != NULL){
                fprintf(stdout, "Current working dir: %s\n", run_dir);
        return 0;
 $ gcc -o getpwd getpwd.c 
 $ ./getpwd 

Leave a Comment