chdir(), fchdir() and getcwd() in C


When working to build any software we could be working with different files stored at different locations and thus there might be cases when we would need to change our current working directory.

C language provides us two functions that help us to change our current working directory these functions are chdir() and fchdir().These functions are included in the unistd.h header file so in order to use these functions we need to include this header file into our program. To verify the changes due to the above two functions, we use getcwd() function of C.

<unistd.h> header file:

The <unistd.h> header defines miscellaneous symbolic constants and types, and declares miscellaneous functions.It contains the chdir() and fchdir() functions. For further reference see here

chdir():

The chdir function is used to change the current working directory of the program or process by passing the path to the function as shown in the syntax.

Function declaration: int chdir( const char *pathname );

Return value : The function return a integer value ,it returns 0 if the change of directory was successful otherwise it returns -1 and the current working directory remains unchanged and errno is set to to indicate the error type.

Errors:

  1. EACCES :Search permission is denied for any component of the pathname.
  2. ELOOP :Too many symbolic links were encountered in resolving path.
  3. ENAMETOOLONG :The path argument exceeds {PATH_MAX} in length or a pathname component is longer than {NAME_MAX}.
  4. ENOENT :A component of path does not name an existing directory or path is an empty string.
  5. ENOTDIR :A component of the pathname is not a directory.

Example code:

#include<stdio.h>
#include<unistd.h>
int main()
{
    //pass your path in the function
    int ch=chdir("xxx");
    /*if the change of directory was successful it will print successful otherwise it will print not successful*/
    if(ch<0)
    printf("chdir change of directory not successful\n");
    else
    printf("chdir change of directory successful");
    return 0;
}

fchdir()

The fchdir function is similar to the chdir function but in this we pass a file descriptor as the function parameter.A file descriptor is a number that uniquely identifies an open file in a computer's operating system. It describes a data resource, and how that resource may be accessed.

Function declaration :

int fchdir(int fd); 

Function return : The function return a integer value ,it returns 0 if the change of directory was successful otherwise it returns -1 and the current working directory remains unchanged and errno is set to to indicate the error type.

Errors:

  1. EACCES :Search permission is denied for the directory referenced by fildes.
  2. EBADF :The fildes argument is not an open file descriptor.
  3. ENOTDIR :The open file descriptor fildes does not refer to a directory.
  4. EINTR :A signal was caught during the execution of fchdir().
  5. EIO :An I/O error occurred while reading from or writing to the file system.

Example code:

#include<stdio.h>
#include<unistd.h>
int main()
{
    //pass your file descriptor in the function
    int ch=fchdir("file descriptor");
    /*if the change of directory was successful it will print successful otherwise it will print not successful*/
    if(ch<0)
    printf("fchdir change of directory not successful\n");
    else
    printf("fchdir change of directory successful");
    return 0;
}

To verify if the above functions are actually changing the directories, we need to check the current working directory just before and after the function call.

How to check the current working directory?

After using the chdir() function we might need to verify whether out current working directory has been changed or not for this we use the getcwd() function.

getcwd():

The getcwd() function places an absolute pathname of the current working directory in the array pointed to by buf, and returns buf. The size argument is the size in bytes of the character array pointed to by the buf argument. If buf is a null pointer, the behaviour of getcwd() is undefined.The return value represent our current working directory.

Function declaration:

char *getcwd(char *buf, size_t size);

Function return :The getcwd() function returns a pointer which points to a character array where the path of current working directory is stored.In case the path is not found then it returns a null pointer and the contents of the array are undefined and the errno is set to indicate the type of error.

Type of errors in getcwd():

1.EINVAL:The size argument is 0.
2.ERANGE:The size argument is greater than 0, but is smaller than the length of the pathname +1.
3.EACCES:Read or search permission was denied for a component of the pathname.
4.ENOMEM:Insufficient storage space is available.

Example code:

#include <unistd.h>
#include <stdio.h>
int main() {
  char cwd[256];


    if (getcwd(cwd, sizeof(cwd)) == NULL)
      perror("getcwd() error");
    else
      printf("current working directory is: %s\n", cwd);
   
   return 0;   
  
}

Using getcwd() to check changes made by chdir():

We can use getchd() to check whether after using the chdir() function the desired changes have been made or not.We first need to make the desired changes using the chdir() function and then use the getcwd() function to see whether the current working directory is the same as desired or not.

C code to check the changes made by chdir():

#include<stdio.h>
#include<unistd.h>
int main()
{
  char cwd[256];

  if (chdir("Your desired path") != 0)
    perror("chdir() error()");
  else {
    if (getcwd(cwd, sizeof(cwd)) == NULL)
      perror("getcwd() error");
    else
      printf("current working directory is: %s\n", cwd);
  }  
}

With this, you have the complete idea of using chdir() and fchdir() and validate the result or changes using getcwd(). Enjoy.