chdir()

Change the current working directory

Synopsis:

#include <unistd.h>

int chdir( const char* path );

Arguments:

path
The new current working directory.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

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

Returns:

0
Success.
-1
An error occurred (errno is set).

Errors:

EACCES
Search permission is denied for a component of path.
ELOOP
Too many levels of symbolic links or prefixes.
ENAMETOOLONG
The path argument is longer than PATH_MAX, or a pathname component is longer than NAME_MAX.
ENOENT
The specified path doesn't exist, or path is an empty string.
ENOMEM
There wasn't enough memory to allocate a control structure.
ENOSYS
The chdir() function isn't implemented for the filesystem specified in path.
ENOTDIR
A component of path is not a directory.

Examples:

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

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

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

Classification:

POSIX 1003.1

Safety:
Cancellation point No
Interrupt handler No
Signal handler Yes
Thread Yes

Caveats:

There's only one current working directory per process. In a multithreaded application, any thread calling chdir() will change the current working directory for all threads in that process.

See also:

errno, fchdir(), getcwd(), mkdir(), rmdir()