C Reference ยท POSIX and Systems
C open(), read(), write() and close() functions
Reference for open(), read(), write(), close() and lseek(): flags and modes, partial transfers, error handling with errno, and when to use them instead of stdio.
These four functions are the lowest layer of file I/O on POSIX systems. open() turns a path into a small non-negative integer called a file descriptor; read() and write() move raw bytes through it; close() releases it. There is no buffering, no formatting and no FILE object. The same calls work on regular files, pipes, sockets, terminals and devices.
stdio functions such as fopen and fprintf are built on top of them. Use the raw calls when you need exact control: permissions at creation time, exclusive creation, non-blocking I/O, or descriptors for pipes and sockets.
#include <fcntl.h> #include <unistd.h> int fd = open("data.txt", O_RDONLY); char buf[100]; ssize_t n = read(fd, buf, sizeof buf); close(fd);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
#include <fcntl.h> #include <unistd.h> int open(const char *path, int flags, ... /* mode_t mode */); ssize_t read(int fd, void *buf, size_t count); ssize_t write(int fd, const void *buf, size_t count); int close(int fd); off_t lseek(int fd, off_t offset, int whence);
| Name | Description |
|---|---|
path |
File to open. |
flags |
Exactly one of O_RDONLY, O_WRONLY, O_RDWR, combined with the | operator and others such as O_CREAT, O_TRUNC, O_APPEND, O_EXCL, O_NONBLOCK, O_CLOEXEC. |
mode |
Required with O_CREAT: the permission bits (for example 0644), reduced by the process umask. |
fd |
The descriptor. |
buf, count |
The memory to fill or send, and its size in bytes. |
offset, whence |
Position and base for lseek: SEEK_SET, SEEK_CUR, SEEK_END. |
Returns: open returns a descriptor (the lowest unused number) or -1. read returns the number of bytes read, 0 at end of file, or -1. write returns the number of bytes written or -1. close and lseek return 0 / the new offset, or -1.
Errors (examples): ENOENT (no such file), EACCES (permission denied), EEXIST (O_EXCL and it exists), EISDIR, EMFILE (too many open files), EINTR (interrupted by a signal), EAGAIN (non-blocking and nothing available), ENOSPC (disk full), EBADF (bad descriptor).
Usage notes
- Short counts are normal.
readmay return fewer bytes than asked, especially on pipes, sockets and terminals, andwritecan write fewer. Loop until you have transferred everything, and treatread() == 0as end of file. - Always check for
-1, and compareerrnowithEINTRto retry. Do not testif (fd): descriptor0is valid (standard input). - The numbers 0, 1 and 2 are standard input, output and error. A newly opened file usually gets 3.
- A descriptor leak (forgetting
close) eventually fails withEMFILE. Closing twice is a bug: the number may already belong to another file. O_CREATwithout the third argument is undefined behavior: the mode would be garbage.O_CREAT | O_EXCLmakes creation atomic and is the safe way to create lock or temporary files.- Writes with
O_APPENDatomically go to the current end of file, even with several writers. - Text is just bytes here: there is no newline translation and no terminating
'\0'. Add the terminator yourself before using a buffer as a string. - Do not mix
readon a descriptor withfreadon aFILE *made from it unless you understand the buffering; usefdopento convert deliberately. fsync(fd)forces data to disk;closedoes not.preadandpwriteread or write at an explicit offset without moving the file position, which suits multi-threaded code.
Related
- unistd.h, stat, pipe
- fopen, fclose, errno.h
- Tutorial: System calls, File handling