What's the difference between a file descriptor and file pointer?
A file descriptor is a low-level integer "handle" used to identify an opened file (or socket, or whatever) at the kernel level, in Linux and other Unix-like systems.
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.
You pass FILE
pointers to standard C functions such as fread()
and fwrite()
.
One is buffered (FILE *
) and the other is not. In practice, you want to use FILE *
almost always when you are reading from a 'real' file (ie. on the drive), unless you know what you are doing or unless your file is actually a socket or so..
You can get the file descriptor from the FILE *
using fileno()
and you can open a buffered FILE *
from a file descriptor using fdopen()
A file descriptor is just an integer which you get from the POSIX open()
call. Using the standard C fopen()
you get a FILE
struct back. The FILE
struct contains this file descriptor amongst other things such as end-of-file and error indicator, stream position etc.
So using fopen()
gives you a certain amount of abstraction compared to open()
. In general you should be using fopen()
since that is more portable and you can use all the other standard C functions that uses the FILE
struct, i.e., fprintf()
and family.
There are no performance issues using either.