linux-sysprog · intermediate · ~15 min

Write with raw descriptors

Create and write a file through descriptors.

Challenge

Create (or overwrite) a file and write to it through the raw descriptor layer: open/write/close.

Task

Implement int posix_write(const char *path, const char *data, int n) that opens path for writing, creating it if absent and truncating it if it exists, writes n bytes from data, closes it, and returns the number of bytes written. Return -1 on failure.

Input

  • path: file to create or overwrite.
  • data: source bytes.
  • n: number of bytes to write.

Output

The byte count written, or -1 if open fails.

Example

posix_write("out.txt", "abcd", 4)   ->   4   (out.txt now contains "abcd")

Edge cases

  • Existing file is truncated to empty before writing.

Rules

  • Open with O_WRONLY|O_CREAT|O_TRUNC (mode 0644). Close before returning.

Input format

path: file path; data: source bytes; n: byte count to write.

Output format

Bytes written, or -1 if open fails.

Constraints

Create/truncate via O_CREAT|O_TRUNC, mode 0644; close on success.

Starter code

#include <fcntl.h>
#include <unistd.h>

int posix_write(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.