Fetching the Current Path

The C library hosts many file and directory management functions. They’re all pretty standard, no matter which operating system you use. What isn’t standard, however, is the size of a pathname. That value plays an important role if you’re to properly allocate memory to store directory information.

In my book, Beginning Programming with C For Dummies, I did not properly allocate memory for a path. Nope, I just guessed. In Exercises 23-5 and 23-6 I use the immediate value 255 for a buffer to hold the current directory.

An option better than just guessing is to use the PATH_MAX constant. It’s defined in the limits.h header file.

One of the reasons I didn’t use PATH_MAX in my book is that it’s not available on all systems, which would require further explanation and a solution similar to what’s presented in this Lesson.

In the following code, PATH_MAX is used to create storage for the current working directory. The code uses preprocessor directives (covered in last week’s Lesson) to determine whether PATH_MAX exists. If so, its value is used, otherwise the pulled-it-out-of-thin-air value of 255 is set.

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

#ifndef PATH_MAX
#define PATH_MAX 255
#endif /* PATH_MAX */

int main()
{
    char *path;

/* Allocate memory for the current path */
    path = (char *)malloc(PATH_MAX);
    if( path == NULL)
    {
        perror("Unable to allocate memory");
        exit(1);
    }

/* Fetch and display directory pathname */
    getcwd(path,PATH_MAX);
    printf("Current directory is '%s'\n",path);

    return(0);
}

This code uses malloc() to allocate storage for the current working directory’s path. That way an overflow won’t occur and I’m not wasting more space than is necessary.

Here’s sample output:

Current directory is '/Users/dang/prog/c/blog'

Seeing how ancient the C language is getting, it’s easy to understand that PATH_MAX isn’t the only constant available to check how large the current path buffer can be. Another constant, MAXPATHLEN, is available. It’s defined in the sys/param.h header file.

In next week’s Lesson, I’ll compare the PATH_MAX and MAXPATHLEN constants to see whether they differ. I’ll also present an alternative to this Lesson’s code that uses only one statement to perform the same task.