尝试创建自己的ls命令,使用stat结构提取文件的inode数量,但是连续失败。这是我的代码:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
int main(int argc, char* argv[])
{
DIR *mydir;
struct dirent *myfile;
struct stat mystat;
mydir = opendir("./");
int print = 0;
while((myfile = readdir(mydir)) != NULL)
{
printf("%ld %s\n", mystat.st_ino , myfile->d_name);
}
closedir(mydir);
}
以下是我得到的输出:
140734253789760 ls.c
140734253789760 ..
140734253789760 .
140734253789760 pwd.o
140734253789760 ls.o
140734253789760 Untitled Document
140734253789760 test.c
140734253789760 usr
140734253789760 ls
140734253789760 pwd
140734253789760 install_flash_player_11_linux.x86_64.tar.gz
140734253789760 readme.txt
140734253789760 pwd.c
140734253789760 Assignment-01-Scripting.pdf
140734253789760 LGPL
140734253789760 test.o
140734253789760 s1.sh
140734253789760 libflashplayer.so
现在,如果我在终端,我得到了这个:
655636 . 1060694 LGPL 680478 ls.o 674765 readme.txt 680539 Untitled Document
674665 .. 680512 libflashplayer.so 680562 pwd 680524 s1.sh 1060712 usr
680479 Assignment-01-Scripting.pdf 680503 ls 684547 pwd.c 684552 test.c
674770 install_flash_player_11_linux.x86_64.tar.gz 684548 ls.c 680510 pwd.o 680589 test.o
答案 0 :(得分:2)
Stat无法获取inode编号,因为它未被任何文件初始化,使用以下代码的文件对其进行初始化:
DIR *mydir;
struct dirent *myfile;
struct stat mystat;
if (stat(myfile->d_name, &mystat) == -1)
{
perror("stat");
exit(EXIT_FAILURE);
}
printf("%ld %s\n",(long) mystat.st_ino , myfile->d_name);