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

CLinuxUnixFilePosix

C Problem Overview


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?

C Solutions


Solution 1 - C

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

Solution 2 - 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)

Solution 3 - C

  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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhil MillerView Question on Stackoverflow
Solution 1 - CPhil MillerView Answer on Stackoverflow
Solution 2 - CMark GerolimatosView Answer on Stackoverflow
Solution 3 - CJim HawkinsView Answer on Stackoverflow