Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interaction of POSIX file descriptors and C FILEs

I'm reading the POSIX specification and I can't fully understand how file descriptors, file descriptions and streams interact.

FILE* f1 = fopen("a.txt", "r");
int fno = fileno(f1);
FILE* f2 = fdopen(fno, "r");

// is it true?
assert(fileno(f2) == fno);

// does it close only f1 or f2 too?
fclose(f1);
fgetc(f2); // valid?

(Question is in the comments.)

like image 841
Yakov Galka Avatar asked Jan 22 '26 23:01

Yakov Galka


1 Answers

The C standard library gives you the opaque pointer FILE*, a file handle, which you can manipulate with fopen()/fclose(), and access with fread()/fwrite().

POSIX offers a notion of file descriptors which are integers. You can manipulate those with open()/close(), and access with read()/write().

For every open file handle FILE * fp on a POSIX system, you can get the underlying file descriptor with fileno(fp). Conversely, for an existing file descriptor n, you can open a standard file handle with fdopen(n).

In other words, the POSIX file descriptors are an operating system primitive which is used to implement the C standard io library. Note that POSIX file descriptors also serve as handles for sockets.

Your final call to fgets() is undefined because the fclose() invalidates the file handle, and consequently its underlying file descriptor. fdopen() does not duplicate the file descriptor.

like image 169
Kerrek SB Avatar answered Jan 25 '26 12:01

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!