Changing the Current Directory

In order to change the current directory for the program, the function chdir(2) can be used. The synopsis for this function is as follows:

#include <unistd.h>

int chdir(const char *path);

This function simply accepts the pathname of the directory that is to become the current directory. To be successful, the current process must have execute access to the directory name given. When successful, the value 0 is returned. Otherwise, -1 is returned, and errno contains the error code.

The following shows how a program can change to the games home directory:

if ( chdir("/home/games") == -1 ) {
    fprintf(stderr,"%s: chdir(2)\n",strerror(errno));
    exit(13);
}

If the chdir(2) call fails, this program reports the error and ...

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.