|
CS456 - Systems Programming
Spring 2026
|
Displaying ./code/feb26/stat.c
/*
gives information about a specified file
> man 2 stat - to view general information about this system call
> man 3 stat - to view the stat structure itself
there are a few variants of stat, only difference between them is what type of argument it takes
- stat : takes pathname from argv
- fstat: takes a file descriptor (from open system call)
- lstat: same as stat, but if pathname is a symbolic link, it returns information about the link
itself, not the file it refers to.
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char **argv){
if(argc < 2){
fprintf(stderr, "Usage %s file\n", argv[0]);
exit(1);
}
int fd;
fd = open(argv[1], O_RDONLY); //using open system call
if(fd == -1){
fprintf(stderr, "ERROR: Cannot open %s, file probably does not exist.\n", argv[1]);
exit(-1);
}
struct stat st;
fstat(fd, &st); //since we have a file descriptor, we'll use the fstat variant
//we wont be able to get info on links themselves unless we use lstat
printf("Device: %ld\n", st.st_dev); // the device where the file resides
printf("Inode: %lu\n", st.st_ino); // inode number, a unique integer identifier assigned to
// every file or directory within a specific Linux/UNIX
// filesystem
printf("Mode: %o\n", st.st_mode); // file mode, contains the type of file (regular, directory,
// link) as well as the file permissions. generally
// represented in octal.
printf("Number of Hard Links: %ld\n", st.st_nlink); // number of hard links to the file
printf("User ID of Owner: %d\n", st.st_uid); //user ID of the owner of the file
printf("Group ID of Owner: %d\n", st.st_gid); //group ID of the owner of the file
printf("Device ID (if special file): %ld\n", st.st_rdev);
// used if this file represents a device (like something in /dev)
printf("File Size: %ld\n", st.st_size); //size of file in bytes
printf("Blocksize for filesystem I/O: %ld\n", st.st_blksize); // number of blocks allocated to file,
// usually in 512-byte units
//these values come from the timespec struct
// read "man timespec" for more info
// st values come from define statements within stat struct
printf("Last Access: %ld\n", st.st_atime); // time of last access
printf("Last Modified: %ld\n", st.st_mtime); // last modification
printf("Last Status Change: %ld\n", st.st_ctime); // time of last change to inode
//more info can be found in man 7 inode
close(fd);
return 0;
}
|