Domanda

Does a file descriptor behave exactly the same as a file pointer except that they are of different types? Then why do we need both of them and, as a result, so many "duplicated" functions like open and fopen, close and fclose? Wouldn't it be simpler if we always use only fd or fp, and then we'll have less to memorize?

È stato utile?

Soluzione

A file descriptor is a raw handle to an open "file" (I say "file", because many things which are not strictly speaking files use the file I/O support, which is a basic level of device I/O support).

A file pointer is a wrapper around a descriptor (that is, a layer on top of the basic I/O provided by the fd APIs) that enables the APIs which use it to do much more than simply read, write, flush, query and close the device. Things such as buffering. Basically, the pointer is to a memory context where other useful things relating to the specific instance of the open file can be stored. Think of it as really primitive OOP before OOP had language support.

And for 99.999% of your programming you need never use the fd; I programmed C full time on 3 different platforms for about 10 years, and in that time I believe I might have use an fd about, maybe, a dozen times.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top