file-handling · intermediate · ~15 min

Is it a regular file?

Inspect the file-type bits of st_mode.

Challenge

Tell whether a path is an ordinary file (as opposed to a directory, device, etc.).

Task

Implement int is_regular_file(const char *path) that returns 1 if path is a regular file, using stat() and the S_ISREG macro, and 0 otherwise.

Input

path: a path the grader sets up (a real file, a directory, or a missing name).

Output

Return 1 for a regular file, 0 for anything else — including directories and the case where stat fails.

Example

regular file   ->   1
"."            ->   0   (directory)
missing path   ->   0

Edge cases

  • Directory: 0.
  • Missing path (stat fails): 0.

Rules

  • S_ISREG(st.st_mode) decodes the file-type bits; return 0 if stat fails.

Input format

path: a filesystem path.

Output format

1 if a regular file, else 0 (including stat failure).

Constraints

Use stat() + S_ISREG; return 0 on stat failure.

Starter code

#include <sys/stat.h>

int is_regular_file(const char *path) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.