-1

How can I get directory name if I know it's inode number? Need the code. Thanks.

the below code passed dir_name by .. , then I got it's i-node number, but what I also want is the directory name.

/*child stat*/
stat(dir_name, &sb);
if (stat(dir_name, &sb) == -1) {
    perror("stat");
    exit(EXIT_FAILURE);
}
childIno = (long) sb.st_ino;
Mahonri Moriancumer
  • 5,993
  • 2
  • 18
  • 28
LuckyLast
  • 61
  • 2
  • 10

2 Answers2

1

Unless you have an index mapping inodes to names, you will have to recursively walk the directory structure until you find a name with the inode you're looking for (which you may not find).

If one part of your program already knows the name of the directory, you should find a way to pass it into your code.

Gabe
  • 84,912
  • 12
  • 139
  • 238
0

Not sure you can easily get it from the inode number alone. Lots of things could point to the same inode (hard links, soft links etc). If you are just looking for a path you can print out and feel good about, you could use realpath. Example below compiles readily on Ubuntu 12.04 and should work on BSD systems as well. realpath will eat all of the ../ and ./ stuff resulting in a decent looking path (though not necesarily a unique path.

#include <stdlib.h>
#include <stdio.h>

int main( int argc, char *argv[] ){
  char *test_path = realpath( "..", NULL );

  if ( test_path ) {
    printf( "Path resolves to %s\n", test_path );
  } else {
    printf( "Couldn't resolve path\n" );
  }

  exit(0);
}
tad
  • 506
  • 3
  • 7