typestar

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

  1. S_ISDIR and S_ISREG read the mode bits.
  2. st_size is bytes; st_mtime is the modification time.
  3. A -1 return means the path could not be examined.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 2 in Files & directories, step 11 of 14 in Systems programming.

← Previous Next →