chdir() — Change the working directory

Standards

Standards / Extensions C or C++ Dependencies

POSIX.1
XPG4
XPG4.2
Single UNIX Specification, Version 3

both  

Format

#define _POSIX_SOURCE
#include <unistd.h>

int chdir(const char *pathname);

General description

Makes pathname your new working directory.

Returned value

If successful, chdir() changes the working directory and returns 0.

If unsuccessful, chdir() does not change the working directory, returns -1, and sets errno to one of the following values:
Error Code
Description
EACCES
The process does not have search permission on one of the components of pathname.
ELOOP
A loop exists in symbolic links. This error is issued if the number of symbolic links detected in the resolution of pathname is greater than POSIX_SYMLOOP (a value defined in the limits.h header file).
ENAMETOOLONG
pathname is longer than PATH_MAX characters, or some component of pathname is longer than NAME_MAX characters while _POSIX_NO_TRUNC is in effect. For symbolic links, the length of the pathname string substituted for a symbolic link exceeds PATH_MAX. The PATH_MAX and NAME_MAX values are determined using pathconf().
ENOENT
pathname is an empty string, or the specified directory does not exist.
ENOTDIR
Some component of pathname is not a directory.

Example

CELEBC10
⁄* CELEBC10 *⁄
#define _POSIX_SOURCE
#include <unistd.h>
#undef _POSIX_SOURCE
#include <stdio.h>

main() {
  if (chdir("⁄tmp") != 0)
    perror("chdir() to ⁄tmp failed");
  if (chdir("⁄chdir⁄error") != 0)
    perror("chdir() to ⁄chdir⁄error failed");
}
Output
chdir() to /chdir/error failed: No such file or directory

Related information