C: 关闭文件* - 不是文件描述符

C: close FILE* - not filedescriptor

我想知道是否可以在不关闭底层文件描述符的情况下释放 FILE 包装器:

void stream_function( int fd ) {
    FILE * stream = fdopen( fd, "r");
    // Read from stream with fread / fscanf
    // then close the buffered stream object with the mythical
    // xclose( stream ) function, leaving the fd intact. 
    xclose( stream );  
}


int main( ) {
   int fd = open("filename" , flags);
   stream_function( fd );
   // Continue to use fd
   close( fd );
}

不是。您可以使用 dup2(fileno(f)) 来保留文件描述符的副本,但是 fclose(f) 本质上总是关闭 fileno(f).

在像您这样的情况下,您使用 fdopen 来获取 FILE *,但是,您可以 dup2 fd,然后再将其传递给 fdopen.这可以防止原始 fd 在 fclose 时间被关闭。