chdir,fchdir,and getcwd Functions

Every process has a current working directory. This directory is where the search for all relative pathnames starts (i.e., with all pathnames that do not begin with a slash(斜线号/)). When a user logs in to a UNIX system, the current working directory normally starts at the directory specified by the sixth field in the /etc/passwd file — the user ’s home directory(用户登录系统后,当前工作目录都从home目录开始). The current working directory is an attribute of a process; the home这里写图片描述 directory is an attribute of a login name. (当前工作目录是进程的属性,home目录是登录用户名的属性)

We can change the current working directory of the calling process by calling the chdir or fchdir function.

chdir, fchdir - change working directory

#include <unistd.h>

int chdir(const char *path);
int fchdir(int fd);
//Both return: 0 if OK, -1 on error

Example:

作为进程的属性之一,当前工作目录(current working directory)不会影响进程调用chdir。因此下图的程序不会出现我们预想的结果:
figure 4.23
如果我们编译该文件为mycd,并如下操作

$pwd
/usr/lib

$mycd
chdir to /tmp succeeded

$pwd
/usr/lib

会发现执行mycd的shell的当前工作目录没有改变。这就是shell执行进程的副作用。每个程序运行在不同的进程中,所有在程序中调用chdir不会影响shell的当前工作目录。因此,chdir必须直接由shell调用,所有cd command被集合进了shells中去。

因为内核必须要知道当前工作目录,我们需要能够获得当前工作目录的内容。不幸的是,内核不保存目录的完整路径。而是保存了目录的信息,如指向目录的v-node的指针。(LInux可以maintain完整的路径名pathname)
下列函数能活的当前工作目录。

getcwd, getwd, get_current_dir_name - get current working directory

#include <unistd.h>

char *getcwd(char *buf, size_t size);
char *getwd(char *buf);
char *get_current_dir_name(void);
//Returns: buf if OK, NULL on error

getcwd我们传入缓冲区buffer的地址,和buffer的尺寸size
buffer需要足够大到能装下决定路径,加上结尾的null字符。否则会返回错误。

Example:改变工作目录并且显示

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <limits.h>
int main(void)
{
    char buf[NAME_MAX];

    if(chdir("/home/feather/feather") < 0)//改变工作目录,需要目录存在,不然报错。
    {
        fprintf(stderr, "chdir error:%s\n", strerror(errno));
        exit(-1);
    }
    if(getcwd(buf, NAME_MAX) < 0)//获得当前的工作目录
    {
        fprintf(stderr, "getcwd error!\n");
        exit(-1);
    }

    printf("cwd = %s \n", buf);
    exit(0);

    return 0;
}

注意:如果chdir中参数是symbolic link那么会跟着进入到链接符号代指的目录。

summary

getcwd在我们运行的应用程序需要返回到开始执行的位置的时候是很有用的。我们可以在改变工作目录之前调用getcwd来保存,在我们完成处理之后,通过调用chdir回到开始的位置。

fchdir提供了更简单的方法。相对于调用getcwd,我们可以打开current working directory并保存文件描述符,之后再跳转到不同的位置。当我们需要返回初始位置的时候,只需要简单的传递file descriptorfchdir中。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猎羽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值