The Purpose of STDIN_FILENO and its Difference from stdin
- Purpose of STDIN_FILENO
STDIN_FILENO belongs to the system API library, declared as an int type. It is an open file descriptor, and its corresponding functions primarily include system calls like open, read, write, close.
File APIs provided at the operating system level all represent files using file descriptors. STDIN_FILENO is the file descriptor for the standard input device (usually the keyboard).
- Differences
-
Inconsistent Data Types:
stdinis of typeFILE*STDIN_FILENOis of typeintFunctions that usestdinprimarily includefread,fwrite,fclose, etc., most of which start with 'f'. Functions that useSTDIN_FILENOincluderead,write,close, etc. -
stdinand similar areFILE*types, belonging to standard I/O, which are high-level input/output functions. They are defined in<stdio.h>.STDIN_FILENOand similar are file descriptors, which are non-negative integers, typically defined as 0, 1, 2. They belong to unbuffered I/O, directly invoking system calls, and are defined in<unistd.h>. -
STDIN_FILENO is the file descriptor for standard input. See
/usr/include/unistd.hfor details. Code: /* Standard file descriptors. / #define STDIN_FILENO 0 / Standard input. / #define STDOUT_FILENO 1 / Standard output. / #define STDERR_FILENO 2 / Standard error output. */ -
Different levels of abstraction.
stdinbelongs to the input stream handled by the standard library, declared as aFILEtype, and its corresponding functions all start with 'f', such as standard library calls likefopen,fread,fwrite,fclose. STDIN_FILENO belongs to the system API library, declared as aninttype. It is an open file descriptor, and its corresponding functions primarily include system calls likeopen,read,write,close.
The standard library encapsulates system API calls; for example, fread internally calls read.
-
File APIs provided at the operating system level all represent files using file descriptors. STDIN_FILENO is the file descriptor for the standard input device (usually the keyboard).
-
I once wondered why an integer file descriptor (fd), like
STDIN_FILENO=0, could represent an open file. Later I understood it's similar to our phone numbers: a phone number is just a 9-digit integer, but within the mobile communication network, it can be used to distinguish different mobile terminals. File operation function libraries provided at the standard C level all useFILE*to represent files, andstdinis aFILE*pointing to the standard input device file.