file-handling · intermediate · ~15 min

Write lines to file

Sequential output with `fopen`/`fputs`/`fclose`.

Challenge

Write an array of strings to a file, one string per line.

Task

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.

Input

  • path: the file path to create/overwrite.
  • lines: an array of n NUL-terminated strings.
  • n: how many strings to write (may be 0).

Output

Returns 0 on success, -1 on failure (e.g. fopen returns NULL). The file ends up containing each string followed by a \n.

Example

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

Edge cases

  • n = 0: create (truncate) the file and write nothing; return 0.
  • If the file cannot be opened, return -1.

Rules

  • Open with mode "w" (truncates). Close the file before returning success.

Input format

A file path, an array of n strings, and the count n (may be 0).

Output format

0 on success, -1 on failure; the file holds each string followed by a newline.

Constraints

Open with "w" (truncate); close before returning success.

Starter code

#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.