网络热词 > fchdir

fchdir

C语言,函数形式:int fchdir(int fd);

返回值:成功返回0,失败返回-1

改变当前工作目录

函数形式:int fchdir(int fd);

返回值:成功返回0,失败返回-1

//Linux环境下(Linux deepin 11.06RC2)测试通过

#include <unistd.h>

#include <stdio.h>

#include <stdlib.h>

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;

}

All rights reserved Powered by 网络热词 87994.com

copyright ©right 2010-2020。
网络热词内容来自网络,如有侵犯请联系客服。zhit325@126.com