How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)? How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)? unix unix

How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?


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)