file-handling · intermediate · ~15 min
Use fwrite to persist raw bytes.
Write a block of bytes to a file, replacing any existing contents.
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.
path: filename to write (created/overwritten in the working directory).data / n: the bytes to write and how many.Return the number of bytes written, or -1 if the file can't be opened.
write_bytes("wb_fixture.txt", "abc", 3) -> 3 (file now contains "abc")
"wb" (binary write, truncates); fwrite with element size 1; close before returning.path: file to write (overwritten). data/n: bytes and count.
int bytes written, or -1 if the file can't be opened.
Open with "wb" (truncates); fwrite with element size 1.
#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.