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?
-
Or you could open the file with open(2), and you would have a file descriptor from the beginning– Antoine PelisseJun 29, 2013 at 16:13
-
11And the inverse: How to get a FILE pointer from a file descriptor?– Michael BurrOct 1, 2013 at 20:35
3 Answers
The proper function is int fileno(FILE *stream)
. It can be found in <stdio.h>
, and is a POSIX standard but not standard C.
-
4Strictly speaking, there wouldn't be any need to mention any headers or libraries if the function was indeed a part of standard C library. However, it is not standard, which is why it might make sense to mention the header at least. Jul 2, 2010 at 23:55
-
22Accessing functions in the standard C library does require including headers, at least if your compiler expects prototypes (I never remember what's actually standard behavior in that respect). Without headers, no names are defined at the beginning of a C file. Jul 3, 2010 at 0:20
-
1@Novelocrat: I didn't mean that there's no need to
#include
anything. I merely meant that it is always easy to find the name of the proper header for a standard function. I.e. it is not really critical to mention the exact header name in the answer. Jul 3, 2010 at 1:51 -
10This is a good answer, but it is worth noting that this isn't a standard c function, it is a posix function. Jul 3, 2010 at 4:00
-
9It is not in the C standard, because file descriptors are a UNIX thing (on Linux, it is open(2), not open(3)). Oct 16, 2014 at 9:08
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.
To answer one of the side questions, to convert a file descriptor to a FILE pointer, use fdopen(3)
-
1I don't believe this was helpful to people searching for this specifically, and this has already been answered in the comment section of OP's post a month before this was written. This is more of a logic clarification as opposed to real information.– kevrFeb 1, 2018 at 15:03
-
12Comments that are sooooper important need to be raised as answers. A huge percent of comments are snarky, pointless metacomments like yours...and this one ;) Jan 15, 2019 at 21:47
-
@MarkGerolimatos this answer is really helpful but would be even more so if you provided more info. Specifically, if I want to read/write to the file descriptor, how to I avoid bypassing stdio's buffer? Thanks!– Max888Nov 20, 2021 at 15:32
fd = _fileno(fp); // Probably the best way
fd = fp->_file; // direct from the FILE structure, member
typedef struct _iobuf {
char* _ptr;
int _cnt;
char* _base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char* _tmpfname; } FILE;