LINUX文件与目录笔记----chdir函数

LINUX文件与目录笔记----chdir函数  

2011-08-15 14:47:49|  分类: linux |  标签:linux  笔记  |举报|字号 订阅

参考书籍:《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]# 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值