参考书籍:《linux编程技术详解》
int chdir(const char *path );
说明:chdir函数用于改变当前工作目录。调用参数是指向目录的指针,调用进程需要有搜索整个目录的权限
错误信息:
EFAULT: path 指向了非法地址
ENAMETOOLNG:路径过长
ENOENT:文件不存在
ENOMEM:内核内存不足
ENOTDIR:给出路径不是目录
EACCES:无访问路径中某个目录的权限
ELOOP:解析路径中太多的符号链接
EIO:发生I/O错误
/*chdir.c:this program using chdirr*/
#include <unistd.h>
#include <iostream>
int main(void)
{
long cur_path_len;
char* cur_work_dir;
if((cur_path_len = pathconf(".",_PC_PATH_MAX)) == -1)
{
perror("Couldn`t get current working path length");
return 1;
}
std::cout<<"Current path length is "<< cur_path_len<<std::endl;
if((cur_work_dir = (char*)malloc(cur_path_len)) == NULL)
{
perror("Couldn't allocate memory for the pathname");
return 1;
}
if (getcwd(cur_work_dir,cur_path_len)==NULL){
perror("Couldn`t get current working directory!");
}
else
{
std::cout<< "Current working directory is"<<cur_work_dir<<std::endl;
}
if (chdir("..") == -1)
{
perror("Couldn`t change current working diretory!");
return 1;
}
if ((getcwd(cur_work_dir,cur_path_len)) == NULL)
{
perror("Couldn`t get current working directory!");
return 1;
}
std::cout<<"After change directory,Current working directory is "<<cur_work_dir<<std::endl;
free(cur_work_dir);
return 0;
}
编译执行结果:
[root@localhost file_dir]# g++ -o chdir chdir.cxx
[root@localhost file_dir]# ls
chdir chdir.cxx getcwd getcwd.cxx pathconf pathconf.cxx
[root@localhost file_dir]# ./chdir
Current path length is 4096
Current working directory is/test/file_dir
After change directory,Current working directory is /test
[root@localhost file_dir]#
修改源程序,给出一个无效的目录
if (chdir("/test/test") == -1)
{
perror("Couldn`t change current working diretory!");
return 1;
}
编译执行结果:
Current working directory is/test/file_dir
Couldn`t change current working diretory!: No such file or directory
[root@localhost file_dir]#