file-handling · intermediate · ~15 min

Write bytes to a file

Use fwrite to persist raw bytes.

Challenge

Write a block of bytes to a file, replacing any existing contents.

Task

Implement int write_bytes(const char *path, const char *data, int n) that writes n bytes from data to the file at path, truncating the file first.

Input

  • path: filename to write (created/overwritten in the working directory).
  • data / n: the bytes to write and how many.

Output

Return the number of bytes written, or -1 if the file can't be opened.

Example

write_bytes("wb_fixture.txt", "abc", 3)   ->   3   (file now contains "abc")

Edge cases

  • The file is truncated, so any prior contents are lost.

Rules

  • Open with "wb" (binary write, truncates); fwrite with element size 1; close before returning.

Input format

path: file to write (overwritten). data/n: bytes and count.

Output format

int bytes written, or -1 if the file can't be opened.

Constraints

Open with "wb" (truncates); fwrite with element size 1.

Starter code

#include <stdio.h>

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

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