chdir函数可以用来切换到其他目录下,这里可用前面学过的getcwd函数来获取当前目录,具体函数如下:
#include <unistd.h>
#include <stdio.h>
#define LENGTH 255
int main(int argc, char *argv[])
{
int ret;
char pwd[LENGTH];
if(argc < 2)
{
printf("\nplease input file path!\n");
return 1;
}
///调用getcwd获取当前目录
if(!getcwd(pwd, LENGTH))
{
perror("getcwd");
return 1;
}
printf("\ngetcwd pwd is %s\n", pwd);
//chdir转入其他目录
printf("change dir...\n", pwd);
ret = chdir(argv[1]);
if(ret)
{
printf("please make sure file path!\n");
return 1;
}
///调用getcwd获取当前目录
if(!getcwd(pwd, LENGTH))
{
perror("getcwd");
return 1;
}
printf("getcwd pwd is %s\n", pwd);
printf("chdir test success!\n");
return 0;
}
在linux中测试如下: