Getting Information About Files
This lesson discusses the utility to get information about files.
Beyond file access, we expect the file system to keep a fair amount of information about each file it is storing. We generally call such data about files metadata. To see the metadata for a certain file, we can use the stat()
or fstat()
system calls. These calls take a pathname (or file descriptor) to a file and fill in a stat
structure as seen in the code snippet below.
struct stat {dev_t st_dev; //ID of device containing fileino_t st_ino; //inode numbermode_t st_mode; //protectionnlink_t st_nlink; //number of hard linksuid_t st_uid; //user ID of ownergid_t st_gid; //group ID of ownerdev_t st_rdev; //device ID (if special file)off_t st_size; //total size, in bytesblksize_t st_blksize; // blocksize for filesystem I/Oblkcnt_t st_blocks; // number of blocks allocatedtime_t st_atime; //time of last accesstime_t st_mtime; //time of last modificationtime_t st_ctime; //time of last status change};
You can see that there is a lot of information kept about each file, including its size (in bytes), its low-level name (i.e., inode number), some ownership information, and some information about when the file was accessed or modified, among other things. To see this information, you can use the command line tool stat
. In this example, we first create a file (called file
) and then use the stat
command line tool to learn some things about the file.
Here is the output on Linux:
prompt> echo hello > fileprompt> stat fileFile: ‘file’Size: 6 Blocks: 8 IO Block: 4096 regular fileDevice: 811h/2065d Inode: 67158084 Links: 1Access: (0640/-rw-r-----) Uid: (30686/remzi)Gid: (30686/remzi)Access: 2011-05-03 15:50:20.157594748 -0500Modify: 2011-05-03 15:50:20.157594748 -0500Change: 2011-05-03 15:50:20.157594748 -0500
Try it out yourself:
Each file system usually keeps this type of information in a structure called an inode. We’ll be learning a lot more about inodes when we talk about file system implementation. For now, you should just think of an inode as a persistent data structure kept by the file system that has information like we see above inside of it. All inodes reside on disk; a copy of active ones are usually cached in memory to speed up access.
Get hands-on with 1400+ tech skills courses.