linux-sysprog · intermediate · ~15 min
Create and write a file through descriptors.
Create (or overwrite) a file and write to it through the raw descriptor layer: open/write/close.
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.
path: file to create or overwrite.data: source bytes.n: number of bytes to write.The byte count written, or -1 if open fails.
posix_write("out.txt", "abcd", 4) -> 4 (out.txt now contains "abcd")
O_WRONLY|O_CREAT|O_TRUNC (mode 0644). Close before returning.path: file path; data: source bytes; n: byte count to write.
Bytes written, or -1 if open fails.
Create/truncate via O_CREAT|O_TRUNC, mode 0644; close on success.
#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.