file-handling · intermediate · ~15 min
Sequential output with `fopen`/`fputs`/`fclose`.
Write an array of strings to a file, one string per line.
Implement int write_lines(const char *path, const char *const *lines, size_t n) that opens path for writing and writes each of the n strings, each followed by a newline. No main — the grader calls it.
path: the file path to create/overwrite.lines: an array of n NUL-terminated strings.n: how many strings to write (may be 0).Returns 0 on success, -1 on failure (e.g. fopen returns NULL). The file ends up containing each string followed by a \n.
write_lines("out.txt", {"alpha","beta","gamma"}, 3)
-> returns 0; file contains "alpha\nbeta\ngamma\n"
write_lines("out.txt", NULL, 0)
-> returns 0; file is empty
n = 0: create (truncate) the file and write nothing; return 0.-1."w" (truncates). Close the file before returning success.A file path, an array of n strings, and the count n (may be 0).
0 on success, -1 on failure; the file holds each string followed by a newline.
Open with "w" (truncate); close before returning success.
#include <stdio.h>
#include <stddef.h>
int write_lines(const char *path, const char *const *lines, size_t n) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.