linux-sysprog · intermediate · ~15 min

Read with raw descriptors

Use the unbuffered fd-based I/O layer.

Challenge

Read a file through the raw descriptor-based I/O layer — open/read/close — instead of stdio (fopen/fread).

Task

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.

Input

  • path: file to read.
  • buf: destination buffer with room for at least n bytes.
  • n: maximum bytes to read.

Output

The byte count read (0..n), or -1 if open fails.

Example

// file "msg.txt" contains "hello"
posix_read("msg.txt", buf, 3)   ->   3   (buf = "hel")
posix_read("missing.txt", buf, 3)   ->   -1

Edge cases

  • Missing file: open returns -1, so return -1.
  • File shorter than n: return the actual count read.

Rules

  • Use open/read/close, not stdio. Close the descriptor before returning.

Input format

path: file path; buf: output buffer; n: max bytes to read.

Output format

Bytes read (0..n), or -1 if open fails.

Constraints

Use POSIX open/read/close; always close on success.

Starter code

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