//
// Created by Eddie on 2020/3/16.
//
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <cstdlib>
#include <cstring>
#include <zconf.h>
ino_t get_inode(char * fname){
struct stat info;
if(stat(fname, &info) == -1){
fprintf(stderr, "Cannot stat");
perror(fname);
exit(1);
}
return info.st_ino;
}
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){//why while?
if(direntp->d_ino == inode_to_find){
strncpy(namebuf, direntp->d_name, buflen);
namebuf[buflen-1] = '\0';
closedir(dir_ptr);
return;
}
}
fprintf(stderr, "%d\n", inode_to_find);
return;
}
void printpathto(ino_t this_inode)
{
ino_t my_inode;
char its_name[BUFSIZ];
if(get_inode(".") != this_inode){
inum_to_name(this_inode, its_name, BUFSIZ);
chdir("..");
my_inode = get_inode(".");
printpathto(my_inode);
printf("/%s", its_name);
}
}
int main(){
printpathto(get_inode("."));
putchar('\n');
return 0;
}
爲啥要cd到上層目錄去找當前目錄的name呢。因爲當前目錄在當前目錄只是.
,是沒有名字的。
爲啥註釋行是while
一直想不明白,返回去看了下目錄那塊,發現確實是while
,代碼手敲一遍確實不一樣,有些細節不會忽略。