Стат не показывает правильные номера инодов

Попытка сделать свою собственную команду ls, используя структуру stat для извлечения номеров инодов из файлов, но постоянный сбой. вот мой код:

#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

Теперь, если я ls -ai в терминале, я получаю это:

 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

1 ответ

Решение

Stat не может получить номер индекса, потому что он не был инициализирован каким-либо файлом, для инициализации его используется следующий код:

     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);
Другие вопросы по тегам