2
votes

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?

1
Printing the filenames (dp->d_name) as well will be enlightening. It's because of the . and .. entries that are in every directory. - Ulfalizer
@Ulfalizer I thought of the same, but 5 + 2 -> 7 so still one is lacking. Maybe a hidden file ... @user: maybe add the result of ls -la in your dir - smagnan
@smagnan: Yeah, dotfile sounds plausible. Or just a typo. :) - Ulfalizer
@user3334375 (re. edit): %s is used to print a string with printf(), not %i. - Ulfalizer
You should also use %ld for the inode number as it's a long integer. - codebeard

1 Answers

4
votes

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.