我有一个通过调用fopen()返回的FILE *。我需要从它获取一个文件描述符,以便在它上进行像fsync(fd)这样的调用。从文件指针获取文件描述符的函数是什么?
发布于 2010-07-03 00:02:07
正确的函数是int fileno(FILE *stream)。它可以在<stdio.h>中找到,并且是POSIX标准,但不是标准C。
发布于 2013-11-14 13:27:07
即使fileno(FILE *)可能返回一个文件描述符,也要非常小心,不要绕过stdio的缓冲区。如果存在缓冲区数据(读取或未刷新写入),则从文件描述符读取/写入可能会给您带来意外的结果。
要回答其中一个次要问题,要将文件描述符转换为文件指针,请使用fdopen(3)
发布于 2021-12-06 02:51:44
  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;https://stackoverflow.com/questions/3167298
复制相似问题