C language to get and change the directory of related functions summary

  • 2020-04-02 03:18:11
  • OfStack

C getcwd() function: gets the current working directory
The header file:


#include <unistd.h>

Definition function:


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

Getcwd () copies the absolute path of the current working directory to the memory space indicated by the parameter buf. The parameter size is the size of buf.

Note:
1. When calling this function, the memory space buf refers to should be large enough. If the string length of the absolute path of the working directory exceeds the size of the parameter, NULL is returned and the errno value is ERANGE.
2. If the parameter buf is NULL, getcwd() will automatically configure the memory according to the size of the parameter (using malloc()). If the parameter size is also 0, getcwd() will determine the configured memory according to the string degree of the absolute path of the working directory.

Return value: on success, copy the result to the memory space indicated by the parameter buf, or return the automatically configured string pointer.

sample


#include <unistd.h>
main()
{
  char buf[80];
  getcwd(buf, sizeof(buf));
  printf("current working directory : %sn", buf);
}

Perform:


current working directory :/tmp


C chdir() : changes the current working directory
The header file:


#include <unistd.h>

Definition function:


int chdir(const char * path);

Chdir () is used to change the current working directory to the directory referred to by the parameter path.

Return value: line returns 0 on success, -1 on failure, errno is the error code.

sample


#include <unistd.h>
main()
{
  chdir("/tmp");
  printf("current working directory: %sn", getcwd(NULL, NULL));
}

Perform:


current working directory :/tmp


C language chroot() function: changes the file root directory
The header file:


 #include <unistd.h>

Definition function:


int chroot(const char * path);

Chroot () is used to change the directory specified by the root as the parameter path. Only the superuser is allowed to change the root, and the child process inherits the new root.

Return value: 0 on success, -1 on failure, error code in errno.

Error code:
1. Insufficient EPERM permissions, unable to change the root directory.
2. The EFAULT parameter path pointer exceeds the accessible memory space.
3. The ENAMETOOLONG parameter path is too long.
4. The directory in the ENOTDIR path exists but is not a real directory.
5. EACCESS is denied access to the directory.
6. ENOMEM is out of core memory.
7. The ELOOP parameter path has too many symbolic connections.
EIO I/O access error.

sample


/*  Change the root directory to /tmp,  And switch the working directory to /tmp */
#include <unistd.h>
main()
{
  chroot("/tmp");
  chdir("/");
}


Related articles: