/*spwd.c 获取当前路径
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
ino_t get_inode(char *);
void printpathto(ino_t);
void inum_to_name(ino_t, char*, int);
int main()
{
printpathto(get_inode("."));
putchar('\n');
return 0;
}
void printpathto(ino_t this_node) //递归打印路径
{
ino_t my_inode;
char its_name[BUFSIZ]; //BUFSIZ 默认缓冲区大小
if(get_inode("..") != this_node){ //判断是否到达"/"
chdir("..");
inum_to_name(this_node, its_name, BUFSIZ); //根据inode号检索文件名 its_name
my_inode = get_inode("."); //获取当前目录inode
printpathto(my_inode);
printf("/%s", its_name);
}
}
void inum_to_name(ino_t inode_to_find, char *namebuf, int buflen)
{
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) //检索到node号
{
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
{
struct stat info;
if(stat(fname, &info) == -1){
fprintf(stderr, "Cannot stat ");
perror(fname);
exit(1);
}
return info.st_ino;
}
《UNIX/LINUX编程实践教程》实例注释chapt4 - spwd
最新推荐文章于 2018-03-14 21:14:14 发布