2

我想知道是否可以在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 );
}
4

1 回答 1

0

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

但是,在像您这样用于fdopen开始FILE *的情况下,您可以dup2在将 fd 传递给fdopen. 这可以保护原始 fd 不被关闭fclose

于 2017-01-29T22:42:19.203 回答