现在的位置: 首页 > 综合 > 正文

C for linux 更改当前工作目录函数 chdir 或 fchdir

2013年04月25日 ⁄ 综合 ⁄ 共 797字 ⁄ 字号 评论关闭

头文件:#include <unistd.h>
用法格式:int chdir ( const char *path );
                  int fchdir ( int fd );

chdir用来将当前工作目录改为参数path指定的目录。
注意:path指针指向的参数一定是连续的路径且不能带空格,否则将会返回 -1 。
例如:
#include <stdio.h>
#include <unistd.h>
int main()//正确的
{
         char s[]="/home";
         chdir (s);
         char xxx[1024];//获取当前目录并打印
         getcwd(xxx,1024);
         printf("The current directory is : %s\n",xxx);
}
打印结果为:/home

int main()//错误的(1)
{
         char s[]="/home~";//为方便我用~代表空格键
         chdir (s);
         char xxx[1024];//获取当前目录并打印
         getcwd(xxx,1024);
         printf("The current directory is : %s\n",xxx);
}
打印结果为:你当前运行此程序的目录

int main()//错误的(2)
{
         char s[]="echo~$HOME";//为方便我用~代表空格键
         chdir (s);
         char xxx[1024];//获取当前目录并打印
         getcwd(xxx,1024);
         printf("The current directory is : %s\n",xxx);
}
打印结果为:你当前运行此程序的目录

fchdir 用来将当前目录改为参数fd(文件描述符)指定的目录。

抱歉!评论已关闭.