Search code examples
cinodeopendirreaddir

C opendir and readdir and inode


I have saved my program in a folder where there are 5 files. Now I want to print the files inode numbers. Here's my program:

#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <libgen.h>
#include <stdlib.h>
#include <string.h>

int main(){
   DIR *dir;
   struct dirent *dp;
    if((dir = opendir(".")) == NULL){
        printf ("Cannot open .");
        exit(1);  
    }
    while ((dp = readdir(dir)) != NULL) {
        printf("%i\n",(*dp).d_ino);
    }
}

and here's my results

251
250
332
254
257
328
274
283

So I have 5 files and 8 i-node numbers? How is it possible?

EDIT: When I add to print this

printf("%i\n",dp->d_name);
printf("%i\n",dp->d_ino);

I get this output

-27246574
251
-27246550
250
-27246526
334
-27246502
254
-27246470
257
-27246438
328
-27246414
274
-27246382
283

So I think that my program doesn't find files in a directory?


Solution

  • d_name is a string:

           struct dirent {
               ino_t          d_ino;       /* inode number */
               off_t          d_off;       /* offset to the next dirent */
               unsigned short d_reclen;    /* length of this record */
               unsigned char  d_type;      /* type of file; not supported
                                              by all file system types */
               char           d_name[256]; /* filename */
           };
    

    So you should printf it with %s, not %i:

    printf("%s %i\n",dp->d_name, dp->d_ino);
    

    Then you'll see what's in there.