Obtaining the Working Directory

As an application writer, you will sometimes want to know what the current directory is from within your C/C++ program. The function getcwd(3) returns this information, and its synopsis is presented as follows:

#include <unistd.h>

char *getcwd(char *buf, size_t size);

char *getwd(char *buf);  /* FreeBSD: For compatibility only */

The function getwd(3) is provided by FreeBSD for compatibility and should not be used in new programs. The getwd(3) function assumes the buffer is of size MAXPATHLEN. If the supplied buffer is shorter than this, then a security breach is possible due to the buffer overrun.

A better function is the getcwd(3) function, which is supported by all modern UNIX systems. The argument buf of length ...

Get Advanced UNIX Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.