CodeBlanks Logo Icon CodeBlanks

File descriptors

Learn the file descriptor concept and management.

File descriptors

A file descriptor (fd) is a small non-negative integer representing an open file. The operating system keeps a descriptor table for each process.

Every process starts with three standard descriptors open: 0 for stdin, 1 for stdout and 2 for stderr. The first newly opened file gets 3. open returns a new descriptor; close releases it.

STDIN_FILENO and friends

unistd.h defines symbolic constants for standard descriptors: STDIN_FILENO (0), STDOUT_FILENO (1) and STDERR_FILENO (2).

These constants replace magic numbers and make code more readable. For example, write(STDOUT_FILENO, msg, n) and write(1, msg, n) are the same, but the first is clearer. New files opened with open get descriptors 3 and above.

Practice Print standard descriptors

Print the values of STDIN_FILENO, STDOUT_FILENO and STDERR_FILENO with printf("%d %d %d\n", ...), separated by spaces. The output must be 0 1 2.

Starter code

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

// Print the three standard descriptors

int main(void) {
    return 0;
}

Sample solution

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

int main(void) {
    printf("%d %d %d\n", STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO);
    return 0;
}

Expected output

0 1 2

Questions and answers

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

1 Print the standard descriptor

Question
int fd = STDIN_FILENO;
printf("%d\n", ____);
Answer
int fd = STDIN_FILENO;
printf("%d\n", fd);

Explanation: You printed the fd variable.

2 Match descriptor values

Term Meaning
0 stdin
1 stdout
2 stderr
3 First open file

3 What is the file descriptor of standard error?

  • 0
  • 1
  • 2 Correct answer
  • 3

Explanation: The stderr descriptor is 2.

All lessons in Advanced