Linux 如何将文件指针 ( FILE* fp ) 转换为文件描述符 (int fd)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3167298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?
提问by Phil Miller
I have a FILE *
, returned by a call to fopen()
. I need to get a file descriptor from it, to make calls like fsync(fd)
on it. What's the function to get a file descriptor from a file pointer?
我有一个FILE *
,通过调用返回fopen()
。我需要从中获取一个文件描述符,以便对其进行调用fsync(fd)
。从文件指针获取文件描述符的函数是什么?
采纳答案by Phil Miller
The proper function is int fileno(FILE *stream)
. It can be found in <stdio.h>
, and is a POSIX standard but not standard C.
正确的函数是int fileno(FILE *stream)
。它可以在 中找到<stdio.h>
,并且是 POSIX 标准,但不是标准 C。
回答by Mark Gerolimatos
Even if fileno(FILE *)
may return a file descriptor, be VERY careful not to bypass stdio's buffer. If there is buffer data (either read or unflushed write), reads/writes from the file descriptor might give you unexpected results.
即使fileno(FILE *)
可能返回文件描述符,也要非常小心不要绕过 stdio 的缓冲区。如果有缓冲区数据(读取或未刷新的写入),则从文件描述符读取/写入可能会给您带来意想不到的结果。
To answer one of the side questions, to convert a file descriptor to a FILE pointer, use fdopen(3)
要回答附带问题之一,将文件描述符转换为 FILE 指针,请使用 fdopen(3)