请输入您要查询的百科知识:

 

词条 fchdir
释义

函数简介

函数名称:fchdir

简介:fchdir是C语言中的一个系统调用函数

功能:改变当前工作目录

头文件:unistd.h

函数形式: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;

}

随便看

 

百科全书收录4421916条中文百科知识,基本涵盖了大多数领域的百科知识,是一部内容开放、自由的电子版百科全书。

 

Copyright © 2004-2023 Cnenc.net All Rights Reserved
更新时间:2025/2/26 23:26:36