Get the current working directory in Unix in C

This C program prints the current working directory in Unix:

#include <stdio.h>
/* For "free". */
#include <stdlib.h>
/* For "getcwd". */
#include <unistd.h>
/* For "strerror". */
#include <string.h>
/* For "errno". */
#include <errno.h>

static void
call_getcwd ()
{
    char * cwd;
    cwd = getcwd (0, 0);
    if (! cwd) {
	fprintf (stderr, "getcwd failed: %s\n", strerror (errno));
    }
    else {
	printf ("%s\n", cwd);
	free (cwd);
    }
}

int
main (int argc, char ** argv)
{
    call_getcwd ();
    return 0;
}

(download)

If getcwd is called with zero arguments, it allocates memory for the directory string.


Copyright © Ben Bullock 2009-2021. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. News about the site. / Privacy / Disclaimer