Lesson 16: File Descriptors — open, read, write
Every file, pipe, socket, and device a program accesses in Linux is represented as a file descriptor — a small integer pointing to an entry in the process's file table. The calls open, read, write, close, and lseek are the most fundamental POSIX I/O primitives. At NVIDIA, model checkpoint files, nvc
A file descriptor is like a table number at a restaurant: you don't need to remember the kitchen address — just give the number and the OS knows exactly which file you mean.
- file descriptor
- A small non-negative integer that identifies an open file within a process. stdin=0, stdout=1, stderr=2. open() returns the lowest available FD.
- open
- System call that opens a file and returns a file descriptor. Takes a path, flags (O_RDONLY, O_WRONLY, O_CREAT, O_TRUNC), and mode for creating new files.
- read
- System call that reads up to n bytes from a file descriptor into a buffer. Returns bytes actually read, 0 at EOF, and -1 on error.
- write
- System call that writes n bytes from a buffer to a file descriptor. Returns bytes actually written — may write less than requested.
- lseek
- System call that repositions the file offset of a descriptor. Allows random-access read/write within a file. SEEK_SET, SEEK_CUR, SEEK_END are whence values.