Change the current working directory
#include <unistd.h> int chdir( const char* path );
libc
The chdir() function changes the current working directory to path, which can be relative to the current working directory or an absolute path name.
#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;
}
}
| Safety: | |
|---|---|
| Cancellation point | No |
| Interrupt handler | No |
| Signal handler | Yes |
| Thread | Yes |
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.
errno, getcwd(), mkdir(), rmdir()