CodeBlanks Logo Icon CodeBlanks

Summary - POSIX

Combine open, read and write to write a file copy program.

The POSIX I/O cycle

In this group you learned the core POSIX I/O tools: opening files with open, reading with read, writing with write and closing with close. File descriptors are at the center of these operations.

Now you will combine them into a real program: write data to a file, read it back and print it. This cycle — open, read or write, close — is the foundation of all POSIX I/O. Even file copying at the OS level uses the same steps.

Practice File round-trip

Open for writing with open("veri.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644). Write data with write(fd, "Merhaba\n", 8) and close(fd). Then open for reading with open("veri.txt", O_RDONLY), read with read(fd2, buf, 8) and write to stdout with write(1, buf, 8).

Starter code

main.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

// Write to veri.txt, read back, print to stdout

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main(void) {
    int fd = open("veri.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644);
    write(fd, "Merhaba\n", 8);
    close(fd);
    int fd2 = open("veri.txt", O_RDONLY);
    char buf[16];
    memset(buf, 0, sizeof(buf));
    read(fd2, buf, 8);
    write(1, buf, 8);
    close(fd2);
    return 0;
}

Expected output

Merhaba

Next steps

You learned POSIX I/O; next comes process management. In the following groups you will see creating processes with fork, replacing programs with exec and waiting with wait.

On these foundations come socket programming, signal handling and multithreading. They are all part of POSIX and use the file descriptor model: sockets are descriptors, so are pipes. The read and write calls you learned will appear everywhere.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What sequence is used for file copying?

  • write, read, close
  • open, read, write Correct answer
  • close, open, read
  • read, write, open

Explanation: First open, then read, then write to copy.

2 Match POSIX calls to roles

Term Meaning
open Opens file
read Reads data
write Writes data
close Closes descriptor

All lessons in Advanced