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.

Press + to interact
struct stat {
dev_t st_dev; //ID of device containing file
ino_t st_ino; //inode number
mode_t st_mode; //protection
nlink_t st_nlink; //number of hard links
uid_t st_uid; //user ID of owner
gid_t st_gid; //group ID of owner
dev_t st_rdev; //device ID (if special file)
off_t st_size; //total size, in bytes
blksize_t st_blksize; // blocksize for filesystem I/O
blkcnt_t st_blocks; // number of blocks allocated
time_t st_atime; //time of last access
time_t st_mtime; //time of last modification
time_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:

Press + to interact
prompt> echo hello > file
prompt> stat file
File: ‘file’
Size: 6 Blocks: 8 IO Block: 4096 regular file
Device: 811h/2065d Inode: 67158084 Links: 1
Access: (0640/-rw-r-----) Uid: (30686/remzi)
Gid: (30686/remzi)
Access: 2011-05-03 15:50:20.157594748 -0500
Modify: 2011-05-03 15:50:20.157594748 -0500
Change: 2011-05-03 15:50:20.157594748 -0500

Try it out yourself:

Terminal 1
Terminal
Loading...

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.