先来说说“工作目录”的概念吧。在程序中所有以文件名引用的文件路径都将被解释为当前工作目录、文件名。
比如:fd=open("./tmp/test.txt",O_RDONLY);
其实shell解释器解释的每一个命令本质上都是一个程序,基本都存放在/bin目录下,但是没有cd这个程序。
改变进程的工作目录函数如下:
#include <unistd.h>
int chdir(char *pathname);
演示改变一个进程的工作目录。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
int fd;
char *p="hello world";
if(chdir("./tmp")==-1)
{
perror("fail to change dir");
exit(1);
}
if((fd=open("test.txt",O_CREAT|O_RDWR))==-1)
{
perror("fail to open");
exit(1);
}
if(write(fd,p,strlen(p))==-1)
{
perror("fail to write");
exit(1);
}
close(fd);
return 0;
}
在同级目录下建立一个空目录,也就是程序中的tmp。编译执行程序后可看到tmp目录下多出一个test.txt的文件夹,文件内容为:"hello world"。