我编写了一个C程序,用于显示用户提供给它的根文件的路径。但是,我在使用opendir / readdir和相应的direntp比较Inode号时遇到问题。主要是,当我使用这些来编写(struct)stat时,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