Coder Perfect

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

Problem

I have a FILE * that was returned by fopen (). I need a file descriptor from it so that I can make fsync(fd) calls on it. What function does one use to obtain a file descriptor from a file pointer?

Asked by Phil Miller

Solution #1

The proper function is int fileno(FILE *stream). It can be found in , and is a POSIX standard but not standard C.

Answered by Phil Miller

Solution #2

Even if fileno(FILE *) returns a file descriptor, avoid bypassing stdio’s buffer at all costs. Reads/writes from the file descriptor may produce unexpected outcomes if there is buffer data (either read or unflushed write).

To respond to one of the side questions, use fdopen to convert a file descriptor to a FILE reference (3)

Answered by Mark Gerolimatos

Solution #3

  fd = _fileno(fp);  // Probably the best way
       fd = fp->_file;     // direct from the FILE structure, member 


    typedef struct _iobuf  {
       char*   _ptr;
       int     _cnt;
       char*   _base;
       int     _flag;
       int     _file;
       int     _charbuf;
       int     _bufsiz;
       char*   _tmpfname; } FILE;

Answered by Jim Hawkins

Post is based on https://stackoverflow.com/questions/3167298/how-can-i-convert-a-file-pointer-file-fp-to-a-file-descriptor-int-fd