I have a FILE *
, returned by a call to fopen()
. I need to get a file descriptor from it, to make calls like fsync(fd)
on it. What's the function to get a file descriptor from a file pointer?
More details can be found in the man page of fdopen : fdopen manual . Get the file descriptor from a FILE pointer (e.g. file ) in C on Linux: int fd = fileno(file); More details can be found in the man page of fileno : fileno manual .
You pass "naked" file descriptors to actual Unix calls, such as read() , write() and so on. A FILE pointer is a C standard library-level construct, used to represent a file. The FILE wraps the file descriptor, and adds buffering and other features to make I/O easier.
A file descriptor is a number that uniquely identifies an open file in a computer's operating system. It describes a data resource, and how that resource may be accessed. When a program asks to open a file — or another data resource, like a network socket — the kernel: Grants access.
If successful, the fileno function returns the file descriptor number associated with an open stream (that is, one opened with the fopen , fdopen , or freopen functions).
The proper function is int fileno(FILE *stream)
. It can be found in <stdio.h>
, and is a POSIX standard but not standard C.
Even if fileno(FILE *)
may return a file descriptor, be VERY careful not to bypass stdio's buffer. If there is buffer data (either read or unflushed write), reads/writes from the file descriptor might give you unexpected results.
To answer one of the side questions, to convert a file descriptor to a FILE pointer, use fdopen(3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With