Course contentsShow
← C
Lesson 1097 of 1,21915. Systems ProgrammingFree lesson

Reading and writing raw bytes

Reading and writing raw bytes

What you'll learn: How to move raw data between your program and the operating system using the read and write system calls.

The "Lower-Level" Way

In earlier lessons, you likely used printf or scanf. These are high-level functions that "format" data—turning an integer into human-readable text. In systems programming, we often need to move data exactly as it is, without any translation.

Think of read and write like a physical conveyor belt. The operating system doesn't care if you are moving pieces of a text file, an image, or a music clip. It simply sees a stream of bytes. Your job is to provide a "bucket" (a buffer) to hold those bytes as they move.

Using read() and write()

To use these system calls, you need three things:

  1. The File Descriptor: The ID of the file or stream (like 0 for input or 1 for output).
  2. The Buffer: A pointer to a memory space (usually a char array).
  3. The Count: How many bytes you want to transfer.

One crucial detail: read and write return the number of bytes they actually processed. If you ask to read 100 bytes but the file only has 10 left, read will return 10. If it returns 0, you’ve reached the end of the file.

A Simple Byte Copier

This code reads up to 128 bytes from standard input (your keyboard) and writes them directly to standard output (your screen).

#include <unistd.h>

int main() {
    char buffer[128];
    ssize_t bytesRead;

    // read() returns the number of bytes it successfully grabbed
    // 0 is the file descriptor for Standard Input
    bytesRead = read(0, buffer, 128);

    if (bytesRead > 0) {
        // write() sends exactly the number of bytes we just received
        // 1 is the file descriptor for Standard Output
        write(1, buffer, bytesRead);
    }

    return 0;
}

Why This Matters

Unlike printf, these functions are "unbuffered." They are direct requests to the kernel. This makes them incredibly fast and flexible. Because they treat everything as a raw byte, you can use the exact same code to copy a .txt file or a .jpg file. You are no longer dealing with "words" or "lines," but with the raw digital fabric of the system.

Key takeaway

The read and write system calls move raw sequences of bytes between file descriptors and memory buffers without any formatting or translation.