chdir改变当前目录

1、在实际应用中,代码需要从当前目录进到其它目录,完成操作,然后再回到当前目录。这个时候需要getcwd获取当前目录路径,保存起来,在使用chdir跳转到其它目录,然后再使用chdir和保存的路径回到最初的目录。


2、man chdir


3、int  chdir(const char *path);

   -参数*path;文件路径

   -返回值;成功返回0,错误返回-1.


4、例:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//chdir和fchdir函数头文件
#include <unistd.h>

#define LENTH 255

int main(int argc,char *argv[])
{
	int ret;
	char pwd[LENTH];

//检测参数	
	if(argc <3){
		printf("\nPlease input file path\n");
		return 1;
	}
	
//getcwd函数获取当前目录		
	if(!getcwd(pwd,LENTH)){
		perror("getcwd");
		return 1;
	}
	printf("\ngetcwd pwd is %s\n",pwd);
	
//使用chdir函数转入其他目录
	ret = chdir(argv[1]);
	if(ret){
		printf("Please make sure file path\n");
		return 1;
	}
	printf("chdir %s is success!\n",argv[1]);
	
//转入其他目录,完成操作
//使用rmdir函数删除目录
	ret = rmdir(argv[2]);
	if(ret<0){
		printf("rmdir %s failed!\n",argv[2]);
		return 1;
	}
	printf("rmdir %s is success!\n",argv[2]);
	
//再次使用chdir回到pwd保存的目录
	ret = chdir(pwd);
	if(ret){
		printf("Please make sure file path\n");
		return 1;
	}
	printf("chdir %s is success!\n",pwd);

	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值