我编写了一个 C 程序,旨在显示从用户给它的根目录开始的文件路径。但是,我在使用 opendir/readdir 和相应的 direntp 比较 Inode 编号时遇到问题。主要是,当我使用这些来编写(结构)统计时,inode 编号与我不使用它们时得到的有很大不同。
我在每一行旁边都放了评论,说明每个人做了什么,并在这篇文章的底部包含了程序的输出。任何解决此问题的帮助将不胜感激。
int main(int argc, char* argv[]){
int found = 0; //declaring stuff
struct stat D;
struct stat ES;
struct dirent* direntD;
struct dirent* direntE;
DIR* dirp;
char currDir[1024];
char newDir[1024];
stat(argv[1], &D); //load the starting directory into a stat struct
printf("loaded %s into D\n", argv[1]); //prints out the directory that has been inputted
printf("Inode number is %ld\n", (long) D.st_ino); //prints out the inode number
strcpy(newDir, currDir); //make the path to the parent directory
strcat(newDir, "/..");
printf("%s\n", currDir); //print out the starting and parent directories
printf("%s\n", newDir);
dirp = opendir(newDir); //open the parent
while ((direntE = readdir(dirp)) != NULL){ //read the files in the parent
printf("%s\n", direntE->d_name); //print names of files in the parent
stat(direntE->d_name, &ES); //load file into stat struct ES
if(ES.st_dev == D.st_dev){ //compare device numbers
printf("st_dev are the same\n"); //if true, print this
if(ES.st_ino == D.st_ino){ //compare inode numbers
printf("st_ino are the same\n"); //if true, print this
printf("The child Dir is %s\n", direntE->d_name); //also print the file/directory in the parent that links to the child
found = 1; //variable that says i've found what i want
} else {
found = 0;
}
} else {
found = 0;
}
printf("%ld\n", (long) ES.st_ino); //printing these to check they both match
printf("%ld\n", (long) D.st_ino);
}
closedir(dirp); //close dir
}
终端输出
./pathto /usr (pathto is the name of my program, starting in root/usr)
loaded /usr into D
Inode number is 131073
/usr
/usr/..
home
0
131073
root
0
131073
..
st_dev are the same
3408247
131073
usr
st_dev are the same
3408247
131073
.
st_dev are the same
3679535
131073