Description: All rights reserved to the author, only for learning exchange, if there are other uses please contact the author, reproduced please follow IT professional norms, please indicate the address of the reprint
The ChDir function is similar to the CD command, which is used to change the current working directory. The specific definition of a function is the following table:
chdir/fchdir function Definition
Header file |
<unistd.h> |
function form |
int chdir (const char *path); int fchdir (int fd); |
return value |
Success |
Failed |
Whether to set errno |
0 |
-1 |
Is |
Description: The parameter of the ChDir function is a string pointer to the directory. For the function to get the desired result, the calling process must have permission to search the entire directory. The Fchdir function requires the same as the ChDir function except that the calling parameter is a file descriptor of the directory.
Error:
(1): Efault:path points to an illegal address.
(2): Enametoolong: The path is too long.
(3): enoent: The file does not exist.
(4): Enomem: Insufficient kernel memory.
(5): Enotdir: The given path is not a directory.
(6): eacces: No access to a directory in the path.
(7): Eloop: Too many symbolic links are encountered in the parsing path.
(8): Eio: An I/O error occurred.
(9): EBADF: Illegal file descriptor (for the Fchdir function).
Instance:
#include <unistd.h>
#include <iostream>
int main (void)
{
Long Cur_path_len = 0;
char *cur_work_dir = NULL;
/* Get directory Maximum length * *
if ((Cur_path_len=pathconf (".", _pc_path_max)) ==-1)
{
Perror ("couldn ' t get current working path length");
return (1);
}
std:: cout << "Current Path Length is" <<cur_path_len << Std::endl;
* * Allocate memory according to the maximum length of the directory obtained
if ((cur_work_dir= (char *) malloc (Cur_path_len)) ==null)
{
Perror ("couldn ' t allocate memory for the pathname");
return (1);
}
if (GETCWD (Cur_work_dir, cur_path_len) = = NULL)
{
Perror ("couldn ' t get current working directory");
return (1);
}
std:: cout << "Current Working Directory is" <<cur_work_dir << Std::endl;
/* Change current working directory to parent directory * *
if (ChDir ("..") = = 1)
{
Perror ("couldn ' t change current working directory");
return (1);
}
if (GETCWD (Cur_work_dir, Cur_path_len) ==null)
{
Perror ("couldn ' t get current working directory");
return (1);
}
std:: cout << "After the ChDir function call, Working Directoryis"
<< cur_work_dir << std:: endl;
Free (CUR_WORK_DIR);
Cur_work_dir = NULL;
return (0);
}