函数名称:fchdir
简介:fchdir是C语言中的一个系统调用函数
功能:改变当前工作目录
函数形式:int fchdir(int fd);
返回值:成功返回0,失败返回-1
//Linux环境下(linux deepin 11.06RC2)测试通过
#include
#include
#include
int main(void)
{
long cur_path_len;
char * cur_work_dir;
int fd;//file descriptor
//get the max length of the directory
if ((cur_path_len = pathconf(".", _PC_PATH_MAX)) == -1)
{
perror("Couldn't get current working path length");
return 1;
}
//print the path length
printf("Current path length is %ld", cur_path_len);
//Allocate memory for the array cur_work_dir
if ((cur_work_dir = (char *) malloc(cur_path_len)) == NULL)
{
perror("Couldn't allocate memory for the pathname");
return 1;
}
//Get current working directory
if (getcwd(cur_work_dir, cur_path_len) == NULL)
{
perror("Couldn't get current working directory");
return 1;
}
//Print the current work directory
printf("Current working directory is %s", cur_path_len);
//free the the memory
free (cur_work_dir);
//Get current file descriptor
if ((fd = open(".", O_RDONLY)) == -1)
{
perror("Couldn't get current file descriptor");
}
//change the current working directory
if (chdir("..") == -1)
{
perror("Couldn't change the current working directory");
return 1;
}
//Allocate memory for the array cur_work_dir
if ((cur_work_dir = (char *) malloc(cur_path_len)) == NULL)
{
perror("Couldn't allocate memory for the pathname");
return 1;
}
//Get current working directory
if (getcwd(cur_work_dir, cur_path_len) == NULL)
{
perror("Couldn't get current working directory");
return 1;
}
//Print the current work directory
printf("Current working directory is %s", cur_path_len);
//free the the memory
free (cur_work_dir);
//Use the function fchdir();
if (fchdir(fd) == -1)
{
perror("functione fchdir error");
return 1;
}
//Allocate memory for the array cur_work_dir
if ((cur_work_dir = (char *) malloc(cur_path_len)) == NULL)
{
perror("Couldn't allocate memory for the pathname");
return 1;
}
//Get current working directory
if (getcwd(cur_work_dir, cur_path_len) == NULL)
{
perror("Couldn't get current working directory");
return 1;
}
//Print the current work directory
printf("Current working directory is %s", cur_path_len);
//free the the memory
free (cur_work_dir);
return 0;
}