open, read, write, and close
Think of using a filing cabinet. First you pull a drawer open. Then you take papers out (read) or put papers in (write), one handful at a time. When you are done, you push the drawer closed so the next person can use the cabinet. These four motions - open, read, write, close - are the entire vocabulary of raw file I/O on a Unix-like system.
These are system calls: you ask the kernel to do the work because only the kernel may touch the disk and the open-file bookkeeping. open(path, flags, mode) finds or creates the file, sets up an entry in your file-descriptor table, and returns a file descriptor (a small integer) or -1 on error. read(fd, buf, count) copies up to count bytes from the file's current position into your buffer buf and returns how many it actually moved (which may be fewer than you asked - a short read). write(fd, buf, count) copies up to count bytes from buf out to the file and returns how many it accepted. close(fd) tells the kernel you are finished, freeing the descriptor for reuse. Both read and write advance the file offset by the number of bytes moved, so repeated calls walk through the file.
Why it matters: this is the bedrock. The friendly fopen/fread/fwrite of the standard library, and higher-level file objects in other languages, are all built on top of these calls. Working at this raw level you must check every return value (a -1 means look at errno), handle short reads and partial writes by looping, and remember to close what you open or you will leak descriptors. The reward is direct, predictable, unbuffered contact with the kernel - exactly what systems code often needs.
int fd = open("out.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644); if (fd < 0) { perror("open"); return 1; } write(fd, "hi\n", 3); close(fd);
Open for writing (create if absent, truncate), write three bytes, close. Always check open's return.
read() returning 0 means end-of-file, not an error; -1 is the error signal (check errno). Never assume read or write moved all the bytes you asked for - loop until done or you hit EOF/an error.