fchdir

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

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

改變當前工作目錄

基本介紹

  • 中文名:fchdir
  • 功能:改變當前工作目錄
  • 頭檔案:unistd.h
  • 語言類型:C語言
函式簡介,示例程式,

函式簡介

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

熱門詞條

聯絡我們