[Previous]
[Contents]
[Next]

chdir()

change the current working directory

Synopsis:

#include <sys/types.h>
#include <unistd.h>
int chdir( const char *path );

Description:

The chdir() function changes the current working directory to the specified path. The path can be either relative to the current working directory, or it can be an absolute path name.

Returns:

0
Success
-1
An error occurred. errno is set to indicate the error, and the current working directory remains unchanged.

Errors:

EACCES
Search permission is denied for a component of path.
ENAMETOOLONG
The argument path exceeds PATH_MAX in length, or a pathname component is longer than NAME_MAX.
ENOENT
The specified path does not exist, or path is an empty string.
ENOMEM
There wasn't enough memory to allocate a control structure.
ENOTDIR
A component of path is not a directory.

Examples:

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

void main( int argc, char *argv[] )
  {
    if( argc != 2 ) {
      fprintf( stderr, "Use: cd <directory>\n" );
      exit( 1 );
    }

    if( chdir( argv[1] ) == 0 ) {
      printf( "Directory changed to %s\n", argv[1] );
      exit( 0 );
    } else {
      perror( argv[1] );
      exit( 1 );
    }
  }

Classification:

POSIX 1003.1

Safety:
Interrupt handler No
Signal handler Yes, but modifies errno
Thread Yes

See also:

chmod(), errno, getcwd(), mkdir(), mknod(), rmdir(), stat(), umask()


[Previous]
[Contents]
[Next]