File descriptors and file pointers under Linux


File descriptors and file pointers under Linux

Document identifier:

First let’s look at what a file identifier is?

File descriptor is a term in computer science. It is an abstract concept used to express references that only want files.

In Linux, each process will save a file descriptor table in the process control block (PCB). The file descriptor is the index of this table, and each table has a reference

Pointer to a file that is already open.

Each Linux process should have three standard file descriptors, corresponding to three standard streams.

Integer value Name (unistd. H) Symbolic Constant (stdio. H) FileStream
0 Standard input STDIN_FILENO stdin
1 Standard output STDOUT_FILENO stdout
2 Standard error STDERR_FILENO stderr

The file descriptor is a non negative integer in form. In fact, it is an index value that points to the record table that the kernel opens the file for each process. Cheng Cheng

When an existing file is opened or a new file is created, the kernel returns a file descriptor to the process. In the process of programming, some low-level programming is often limited

Expand around the file descriptor. But the concept of file descriptors is often only applicable to UNIX, Linux and other operating systems

Operations related to file descriptors:

function operation
File descriptor generation Open (), socket (), pipe (), etc
Operations related to a single file descriptor Read(), write(), send(), fchmod(), etc
Operations related to complex file descriptors Select(), poll(), etc
Operations related to document descriptor table Close(), dup(), etc

File pointer:

File pointer is what we learn in C language. In C language, we use a pointer variable to point to a file, which is called file pointer. Through the file pointer, we can perform various operations on the indicated file. In C language, file pointer is used instead of file descriptor as handle of I / O. The file pointer points to a data structure in the process user area called the file structure. The file structure contains a buffer and a file descriptor.

File pointer c language’s general format, so relatively speaking, more convenient to transplant

We usually get the file pointer:

FILE *fp = fopen("test.txt","r");

After getting the pointer, we can get the information of the file descriptor in the pointer.

The file descriptor is unique, but the file pointer is not unique. The object pointed by the file pointer is unique.

Conversion of file descriptors and file pointers:

int fileno(FILE *stream);

FILE *fdopen(int fd,const char *mode);

The first parameter of fdopen is an open file descriptor. Mode is a string indicating the open mode, which is the same as fopen, such as “W” or “R”

Fileno function, which returns the file descriptor corresponding to the file stream, and – 1 for failure.

Thank you for reading, hope to help you, thank you for your support!