Other Ways to Fetch the CWD

In last week’s Lesson I mentioned the constant, MAXPATHLEN. Like PATH_MAX, it returns the size of the maximum number of characters allowed in a pathname. Unlike PATH_MAX, however, MAXPATHLEN is defined in the sys/param.h header file, not limits.h.

Why the two constants? Who knows!

A better question is to determine whether or not they’re equal. After all, internally one may be assigned to the other. To confirm whether that’s the case, you can go spelunking in the header files, or just write some quick code to compare the values:

#include <stdio.h>
#include <limits.h>
#include <sys/param.h>

int main()
{
	printf("The value of PATH_MAX is %d\n",PATH_MAX);
	printf("The value of MAXPATHLEN is %d\n",MAXPATHLEN);

	return(0);
}

Here is the output on my Mac:

The value of PATH_MAX is 1024
The value of MAXPATHLEN is 1024

By exploring the header files, I found the following line in sys.param.h:

#define MAXPATHLEN      PATH_MAX

There it is! So MAXPATHLEN is directly related to PATH_MAX, which is frequently the case when two constants represent the same value. One constant (probably MAXPATHLEN) is historical and included for backwards compatibility.

While exploring these two constants, I noticed another function for reading the current directory, getwd().

Like getcwd(), the getwd() function also returns the current working directory. It requires the unistd.h header file. It’s a bit more concise than the getcwd() function, and it’s capable of returning a directory in one punch, as the following code demonstrates:

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

int main()
{
	printf("Current directory is '%s'\n",getwd(NULL));

	return(0);
}

So why isn’t everyone using getwd() instead of getcwd()? How could I make such an oversight in my books? Easy.

While using getwd() is pretty nifty, as the one-statement code above demonstrates, it’s not the best function choice for a variety of reasons.

I stumbled upon getwd() as I was exploring the C library man pages. I recommend that you do so as well: Look up an item in the man pages and see the related functions. It’s a great way to expand your C knowledge.

On the man page for getwd() (shared with getcwd()), it states the following:


BUGS
     The getwd() function does not do sufficient error checking and is not
     able to return very long, but valid, paths.  It is provided for compati-
     bility.

The getwd() function apparently had some serious issues, so it was deprecated a while back. The current version is provided for compatibility and it calls getcwd() internally. So if you’re going to learn and use a C library function to fetch the current directory, use getcwd(), which is the function covered in my books.