Open In App

chdir() in C language with Examples

Last Updated : 27 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The chdir command is a system function (system call) that is used to change the current working directory. On some systems, this command is used as an alias for the shell command cd. chdir changes the current working directory of the calling process to the directory specified in path. 

Syntax:

int chdir(const char *path);

Parameter: Here, the path is the Directory path that the user want to make the current working directory.
Return Value: This command returns zero (0) on success. -1 is returned on an error and errno is set appropriately. 
Note: It is declared in unistd.h. 

Example 1: 

C




#include<stdio.h>
 
// chdir function is declared
// inside this header
#include<unistd.h>
int main()
{
    char s[100];
 
    // printing current working directory
    printf("%s\n", getcwd(s, 100));
 
    // using the command
    chdir("..");
 
    // printing current working directory
    printf("%s\n", getcwd(s, 100));
 
    // after chdir is executed
    return 0;
}


Output:
  

Note: The above program changes the working directory of a process. But, it doesn’t change the working directory of the current shell. Because when the program is executed in the shell, the shell follows fork on exec mechanism. So, it doesn’t affect the current shell. 

Example 2: 

C




#include <unistd.h>
#include <stdio.h>
 
// Main Method
int main() {
 
// changing the current
// working directory(cwd)
// to /usr
if (chdir("/usr") != 0)
    perror("chdir() to /usr failed");
 
// changing the cwd to /tmp
if (chdir("/tmp") != 0)
    perror("chdir() to /temp failed");
 
// there is no /error
// directory in my pc
if (chdir("/error") != 0)
 
    // so chdir will return -1
    perror("chdir() to /error failed");
 
return 0;
}


Output:
  

Errors: There can be errors that can be returned. These depend on the filesystem.

  • EACCES: If the search permission is denied for one of the components of the path.
  • EFAULT: If the path points lie outside the accessible address space.
  • EIO: If there is an I/O error occurred.
  • ELOOP: If there are too many symbolic links encountered in the resolving path.
  • ENAMETOOLONG: If the path is too long.
  • ENOENT: If the file does not exist.
  • ENOMEM: If there is insufficient kernel memory available.
  • ENOTDIR: If the component of the path is not a directory.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads