I want to get to a specifIC inode (using its number), within an ext2 image, using the C language. I'm traying to do this by opening the ext2 image with the open() syscall, and then traverse it using lseek() with the right offsets, until I get to the inode. Is this correct? Or am I doing something wrong? I'm a little confused whether using open() is correct, or there is more appropriate functions to do this.
int fd = open("ext2fs.img", O_RDONLY);
assert(fd != -1);
off_t startPosition = lseek(fd, 0, SEEK_CUR);
assert(startPosition != -1);
Should I just add offsets to startPosition until I get to the inodes? But how can I search for a specific inode?
UPDATED (to be more specific)
I already have the layout of the ext2 file system (http://www.nongnu.org/ext2-doc/ext2.html), this gives me everything (all the offsets) important I need. And I need to create a C program to manipulate the metadata and data. Like removing and copying files, for example.
I know what to do, but I'm having trouble implementing it.
For example: To test if I know what I'm doing, I'm trying to read the number of free inodes in an ext2 disk image my professor provided, doing this:
#define SUPER_BLOCK 1024
int main()
{
int freeInodes;
int fd = open("path.img", O_RDONLY);
off_t startPosition = lseek(fd, 0, SEEK_CUR);
lseek(fd, startPosition + SUPER_BLOCK + 16, SEEK_CUR);
read(fd, freeInodes, 4);
printf("Number of free inodes: %d", freeInodes);
}
The output I receive is: "Number of free inodes: 32767"
Am I interpreting the data I got from read() correctly? I have no idea if this value received is correct.
There is no real use case for accessing by inode, except to circumvent file system security. In Linux,
debugfs
allows you to do that. If you think it is an absolute requirement try the source code for debugfs.Consider using the stat() call from file tree walk (ftw()/nftw() ) as a callback, or use stat() + scandir() directly for faster coding. Either will allow you to get all inodes of files you have permissions to stat. And open or whatever.