pwd命令功能为输出当前所在工作目录的绝对路径名称。
绝对路径和相对路径:
绝对路径:从根目录开始直到文件位置
相对路径:相对于程序当前所在目录到文件位置
例:程序运行在C:/user/dell下,假设有一个文件test.txt
绝对路径:C:/user/dell/test.txt
相对路径:./test.txt
man pwd
命令查看pwd的详细功能man -l
和man -p
pwd -l
功能为从环境中执行PWD命令,即使它包含符号链接;pwd -p
功能为避免所有符号链接,执行pwd命令。man -k dir \ grep 2
查看系统调用,我们可以发现getpwd函数,功能为获取当前工作目录man getcwd
命令查看getcwd函数功能
char *getcwd(char *buf, size_t size);
该函数的第一个参数为数组首地址,第二个参数为空间值;#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
char buf[1024];
char *cwd =getcwd(buf, sizeof(buf));
if (cwd == NULL) {
perror("Get cerrent working directory fail.\n");
exit(-1);
} else {
printf("%s\n", cwd);
}
return 0;
}
获取初始目录名称
next:
获取当前目录的icode_number
通过chdir() 返回上一级目录
获得上一级目录的icode_number_ago
icode_number==icode_number_ago ?
不相等:
获取当前目录名称
返回next
相等
已经找到根目录,输出绝对路径
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
ino_t get_inode(char*);
void print(ino_t);
void inum_to_name(ino_t,char*,int);
int main()
{
ino_t node=get_inode(".");
print(node); //打印当前目录绝对路径
putchar('\n');
return 0;
}
void print(ino_t this_inode)
{
ino_t my_inode;
char its_name[BUFSIZ];
/*如果本目录的inode-number与上级目录不同,即本目录不是根目录*/
if (get_inode("..")!=this_inode)
{
chdir(".."); //进入上级目录
inum_to_name(this_inode,its_name,BUFSIZ);
my_inode = get_inode(".");
print(my_inode);
printf("/%s",its_name);
}
}
void inum_to_name(ino_t inode_to_find,char* namebuf,int buflen) //找到inode-number节点对应的文件名,并放在字符数组里
{
DIR* dir_ptr;
struct dirent* direntp;
dir_ptr = opendir(".");
if (dir_ptr == NULL)
{
perror(".");
exit(1);
}
while((direntp = readdir(dir_ptr)) != NULL)
{
if(direntp->d_ino == inode_to_find)
{
strncpy(namebuf,direntp->d_name,buflen);
namebuf[buflen-1] = '\0';
closedir( dir_ptr);
return;
}
}
fprintf( stderr , "error looking for inum % d\n" ,inode_to_find);
exit (1) ;
}
ino_t get_inode(char* fname) //根据文件名,返回inode-number
{
struct stat info;
if ( stat( fname, &info) == -1){
fprintf( stderr , "Cannot stat ");
perror(fname);
exit (1);
}
return info.st_ino;
}
原文:https://www.cnblogs.com/wangzihong0213/p/12024732.html