views:

114

answers:

1

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?

+7  A: 

The proper function is int fileno(FILE *stream). It can be found in <stdio.h>, and is part of the standard C library on UNIX-like systems from SVR2 onwards.

Novelocrat
You need to say what headers must be included and what libraries linked, for this kind of answer to be complete. In this case we're looking at `stdio.h` (almost certainly already included) and the standard c library (which the compiler almost certainly links by default), so there is not trouble, but still.
dmckee
@dmckee: you make a good point. So edited. Once one has a name, though, it's easy enough to read a man-page about it. It's finding that name that's really troublesome.
Novelocrat
Strictly 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.
AndreyT
Accessing 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.
Novelocrat
@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.
AndreyT
This is a good answer, but it is worth noting that this isn't a standard c function, it is a posix function.
Evan Teran