file-handling · beginner · ~15 min

Is a file readable?

Open a file and check the result of fopen.

Challenge

Check whether a file can be opened for reading — the simplest use of fopen's return value.

Task

Implement int file_readable(const char *path) that returns 1 if the file at path can be opened for reading (then closes it again), and 0 otherwise.

Input

path: filename of a file the grader creates in the working directory.

Output

Return 1 if fopen succeeds, 0 if it fails (missing or unreadable file).

Example

existing file   ->   1
missing file    ->   0

Edge cases

  • Missing or unreadable file: 0.
  • If the file opens, close it before returning.

Input format

path: file to test.

Output format

1 if openable for reading, else 0.

Constraints

Close the file if it opened.

Starter code

#include <stdio.h>

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

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