What is the difference / relationship between FILE * and int fd value?

I noticed that in C, file I / O depends on the file descriptor. However, in some standard library functions, such as write(int fd, xxxx)

, a file descriptor is represented as an integer, while in some other functions, such as fseek(FILE *stream, xxxx)

, it is represented as a pointer.

Are int

fd and values ​​the FILE *

same? Why does C leave such a difference?

(I tried to find a similar question but couldn't, although my question seems to be preliminary)

+3


source to share


2 answers


The standard file type in C is FILE *

. Any functions you see with int fd

are an extension, not a C standard. These are usually POSIX extensions .



int

there are file descriptors because that's what the base kernel uses to describe files. On systems where file descriptors are used FILE *

, this is a wrapper around the file descriptor, adding buffering, etc. But not all systems use file descriptors, for example I'm pretty sure Windows doesn't, although I haven't confirmed it yet. In these systems FILE *

, something even more suitable is wrapped there.

+7


source


Are int fd and FILE * values ​​the same?

Not. This is not true.

A file descriptor is int

, whereas FILE *

is a pointer to a file. The main difference is that the latter is buffered while the former is not.



The file pointer ( FILE*

) usually contains more information about the stream, such as the current location, end of the file marker, errors in the stream, etc. But a file descriptor is simply a positive integer representing a "file" (which can be a pipe, socket, or any other stream).

You can get a file descriptor from a file pointer with fileno()

:

int fd = fileno(fp);

      

+9


source







All Articles