一、chdir和fchdir函数
虽然《Unix环境高级编程》一书把chdir和fchdir函数放到文件管理这部分来讲,但严格讲这两个函数不属于文件系统管理的函数,应该属于进程管理的函数。这两个函数用于改变进程的当前工作目录,而进程的当前工作目录是进程的属性,所以它们不属于文件系统管理函数,但它却涉及到文件管理(例如文件的相对路径问题)。所以放到这里来将也是有道理的。
这两个函数原型如下:
#include <unistd.h>
int chdir(const char *pathname);
int fchdir(intf filedes);
返回值:若切换成功则返回0,若出错则返回-1
两个函数的作用都是一样的,只是参数不同罢了。chdir函数用指定路径名切换,而fchdir用一个已经打开的文件描述符(用open函数打开)切换。
当前工作目录可以作为诸如open、creat等文件操作函数相关参数的相对路径的路径前缀。假设"/tmp"为当前工作目录,那么相对路径“myfile”转换为绝对路径就是“/tmp/myfile”。
当文件位于当前工作目录时,open、creat等函数的相关路径参数可以使用用相对路径。
实例 x.4.22.1.c
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main(void)
{
char dirname[] = "/tmp/";
char filename[]= "myfile";
int fp;
if ((fp = open(filename, O_RDONLY)) == -1)
printf("1:open error for %s\n", filename);
else
printf("1:open secceed for %s\n", filename);
if (chdir(dirname) == -1) {
printf("chdir error for %s\n", dirname);
} else {
if ((fp = open(filename, O_RDONLY)) == -1)
printf("2:open error for %s\n", filename);
else
printf("2:open secceed for %s\n", filename);
}
return 0;
}
编译与执行:
[root@localhost unixc]# rm -rf /tmp/myfile myfile
[root@localhost unixc]# ls -l /tmp/myfile myfile
ls: cannot access /tmp/myfile: No such file or directory
ls: cannot access myfile: No such file or directory
[root@localhost unixc]# echo "123456789" > /tmp/myfile
[root@localhost unixc]# ls -l /tmp/myfile myfile
ls: cannot access myfile: No such file or directory
-rw-r--r--. 1 root root 10 Nov 5 08:53 /tmp/myfile
[root@localhost unixc]# cc x.4.22.1.c
[root@localhost unixc]# ./a.out
1:open error for myfile
2:open secceed for myfile
[root@localhost unixc]#
分析:
(1)在当前工作目录切换到“/tmp/myfile”试图用相对路径打开文件“myfile”,结果显示调用失败了
(2)用chdir函数把当前工作目录切换到“/tmp”,此时使用相对路径打开"myfile",结果显示chdir调用成功。
(3)在允许本程序前要确保当前目录没有"myfile"文件,而“/tmp”一定要有“myfile”的存在:
rm -rf /tmp/myfile myfile #强制删除两个文件
echo "123456789" > /tmp/myfile #echo出一个文件
二、getcwd函数
既然能切换当前工作目录,也应当能取得当前工作目录,然后在必要的时候回到切换前的工作目录。getcwd函数就是这个作用,它用于取得当前工作目录。一般切换工作目录都是临时切换然后再切换回来。所以在切换前有必要通过getcwd函数取得当前工作目录并保存下来。
getcwd函数原型:
#include <unistd.h>
char *getcwd(char *buf, size_t size);
返回值:若成功则返回buf,若出错则返回NULL
参数:
buf为存放当前工作目录的缓冲池地址,size为缓冲池的字节数。
实例 x.4.22.2.c
#include <unistd.h>
#include <stdio.h>
int main(void)
{
char dirname[] = "/tmp/";
char cwd[256];
printf("befor chdir:\n");
if(getcwd(cwd, 256) != NULL)
printf("curent work directory:%s\n", cwd);
else
printf("getcwd error!\n");
printf("after chdir:\n");
if (chdir(dirname) == -1) {
printf("chdir error for %s\n", dirname);
} else {
if(getcwd(cwd, 256) != NULL)
printf("curent work directory:%s\n", cwd);
else
printf("getcwd error!\n");
}
return 0;
}
编译与执行:
[root@localhost unixc]# cc x.4.22.2.c
[root@localhost unixc]# ./a.out
befor chdir:
curent work directory:/root/unixc
after chdir:
curent work directory:/tmp
[root@localhost unixc]#