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

标签 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 );
}

最佳答案

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

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

关于C: 关闭文件* - 不是文件描述符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41926760/

相关文章:

c - 如何从 C 中检查目标文件是 COFF 还是 ELF 格式?

c - C 读取输入文件并忽略空行或以 # 开头的行

c - 寻找与英特尔 IPP 进行 FFT 卷积的工作示例

Python 从文件描述符 int 获取文件路径(从 os.open 返回)

c - 同一位置的重复文件指针

c - 信号量问题,不要等待

c++ - Q文件/文件* : How to properly close the handle?

Python - 如何将 "an OS-level handle to an open file"转换为文件对象?

c++ - 如果我在套接字描述符上使用 fdopen() 如何关闭 socket()

c - 在程序执行期间将行写入文本文件 - 更快的方式