linux-sysprog · intermediate · ~15 min
Use the unbuffered fd-based I/O layer.
Read a file through the raw descriptor-based I/O layer — open/read/close — instead of stdio (fopen/fread).
Implement int posix_read(const char *path, char *buf, int n) that opens path read-only, reads up to n bytes into buf, closes the file, and returns the number of bytes read. Return -1 if the file cannot be opened.
path: file to read.buf: destination buffer with room for at least n bytes.n: maximum bytes to read.The byte count read (0..n), or -1 if open fails.
// file "msg.txt" contains "hello"
posix_read("msg.txt", buf, 3) -> 3 (buf = "hel")
posix_read("missing.txt", buf, 3) -> -1
open returns -1, so return -1.n: return the actual count read.open/read/close, not stdio. Close the descriptor before returning.path: file path; buf: output buffer; n: max bytes to read.
Bytes read (0..n), or -1 if open fails.
Use POSIX open/read/close; always close on success.
#include <fcntl.h>
#include <unistd.h>
int posix_read(const char *path, char *buf, int n) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.