file-handling · intermediate · ~15 min

Read the first N bytes

Use fread to pull raw bytes.

Challenge

Read up to N bytes from the start of a file into a buffer.

Task

Implement int read_first_bytes(const char *path, char *buf, int n) that reads up to n bytes from the file at path into buf and returns how many were actually read.

Input

  • path: filename of a file the grader creates in the working directory.
  • buf / n: destination buffer and the maximum number of bytes to read.

Output

Return the number of bytes read (0..n), or -1 if the file can't be opened.

Example

file "rd_fixture.txt" = "hello"
read_first_bytes("rd_fixture.txt", buf, 3)   ->   3   (buf = "hel")
read_first_bytes("missing", buf, 3)          ->   -1

Edge cases

  • File shorter than n: returns the actual (smaller) count.
  • Missing file: -1.

Rules

  • Use fread with element size 1; open in binary mode; close before returning.

Input format

path: file to read. buf/n: buffer and max bytes.

Output format

int bytes read (0..n), or -1 if the file can't be opened.

Constraints

fread with element size 1; binary mode.

Starter code

#include <stdio.h>

int read_first_bytes(const char *path, char *buf, int n) {
    /* TODO */
    return -1;
}

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