Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?

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?

like image 466
Phil Miller Avatar asked Jul 02 '10 16:07

Phil Miller


People also ask

How do I find the FD of a file?

More details can be found in the man page of fdopen : fdopen manual . Get the file descriptor from a FILE pointer (e.g. file ) in C on Linux: int fd = fileno(file); More details can be found in the man page of fileno : fileno manual .

Is file pointer same as file descriptor?

You pass "naked" file descriptors to actual Unix calls, such as read() , write() and so on. A FILE pointer is a C standard library-level construct, used to represent a file. The FILE wraps the file descriptor, and adds buffering and other features to make I/O easier.

What is a file descriptor in C?

A file descriptor is a number that uniquely identifies an open file in a computer's operating system. It describes a data resource, and how that resource may be accessed. When a program asks to open a file — or another data resource, like a network socket — the kernel: Grants access.

Does Fopen return file descriptor?

If successful, the fileno function returns the file descriptor number associated with an open stream (that is, one opened with the fopen , fdopen , or freopen functions).


2 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.

like image 159
Phil Miller Avatar answered Sep 28 '22 11:09

Phil Miller


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)

like image 20
Mark Gerolimatos Avatar answered Sep 28 '22 11:09

Mark Gerolimatos