Inspecting a file in C
stat fills a struct with size, mode and timestamps.
#include <stdio.h>
#include <sys/stat.h>
int describe(const char *path) {
struct stat info;
if (stat(path, &info) != 0) {
perror("stat");
return 0;
}
printf("%s: %lld bytes, mode %o\n", path, (long long) info.st_size,
(unsigned) (info.st_mode & 0777));
printf("directory: %d, regular: %d\n", S_ISDIR(info.st_mode) != 0,
S_ISREG(info.st_mode) != 0);
return 1;
}
How it works
S_ISDIRandS_ISREGread the mode bits.st_sizeis bytes;st_mtimeis the modification time.- A -1 return means the path could not be examined.
Keywords and builtins used here
charconstdescribeifintlongreturnstatstructunsigned
The run, in numbers
- Lines
- 16
- Characters to type
- 362
- Tokens
- 105
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 60 seconds.
Step 1 of 2 in Files & directories, step 11 of 14 in Systems programming.