File Operations in Unix/Linux – Programming Project: Convert File Pathname to Inode

In every file system, almost every operation starts with a filename, e.g.

cat filename

open filename for R|W

copy file1 to file2

etc.

The fundamental problem of every file system is to convert a filename into the file’s representation data structure in the file system. In the case of EXT2/3/4 file systems, it amounts to converting a pathname to the file’ s INODE. The programming project is to integrate the knowledge and programming techniques in the above examples and exercises into a program which finds a file in an EXT2 file system and prints its information. Assume vdisk is a virtual disk containing many levels of directories and files. Given the pathname of a file, e.g. /a/b/c/d, write a C program to find the file and prints its information, such as the file type, owner id, size, date of creation and data block numbers, including indirect and double indirect blocks.

HINTS and helps:

  •  Tokenize pathname into component strings. Denote them as char *name[0], *name[1], .. ,*name[n-1], where n is the number of component strings.
  •  Start from INODE *ip -> root inode (ino=2)
  •  for (int i=0; i<n; i++){

int ino = search(ip, name[i]);

if (!ino) exit(1);                // can’t find name[i]

ip ->inode of name[i];            // ip point at INODE of name[i]

if (*ip is not a DIR) exit(2);     // name[i] is not a DIR

}

  •  If reach here: ip must point at file’ s inode. Use ip-> to access the fields of inode
  •  To print indirect block numbers:

read i_block[12] into a char buf[BLKSIZE];

u32 *up = (u32 *)buf;

*up is an indirect block number; up++ points to the next number, etc.

Similar technique can be used to print double indirect block numbers.

Source: Wang K.C. (2018), Systems Programming in Unix/Linux, Springer; 1st ed. 2018 edition.

Leave a Reply

Your email address will not be published. Required fields are marked *