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

时间:2017-01-29 22:38:38

标签: c fdopen

我想知道是否可以在不关闭底层文件描述符的情况下发布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 );
}

1 个答案:

答案 0 :(得分:0)

不是。您可以使用dup2(fileno(f))保留文件描述符的副本,但fclose(f)本身并始终关闭fileno(f)

如果您使用fdopen来开始使用FILE *,那么您可以在将dup2传递给{{1}之前{f}} }。这可以保护原始fd在fdopen时不被关闭。

相关问题