file descriptor vs file handle

Dr. Richard Glass reg at pinet.aip.org
Thu Feb 28 06:27:25 AEST 1991


In article <27C9CB35.5F7 at wilbur.coyote.trw.com> cwong at charlie.coyote.trw.com (Chun Wong) writes:
>Can someone distinguish the differences between a file descriptor and
>a file handle?  I know that creat returns a file handle whereas fopen
>returns a file descriptor.  What's the difference?  Are they interchangeable?
>
>-C. Wong

I think what you want to know is what the difference between the IO
routines read, write, creat versus fgets, fopen etc.  The first set of
routines are also known as Level I IO and "raw data movers".  They
perform NO translation of data andd read/write at the byte level.  For example,
doing a write(fd, &(x=0), sizeof(int) ) where x is an int will write
"sizeof int"  NUL ASCII characters. An fputc( x = 0,stream) will write
the ASCII code for the character 0.  The f - routines are the level 2
IO.  They are the C language IO functions.  Since C migrated from the
UNIX enviornment, some of the UNIX kernal routines "became" part of the
library in particular the level I IO routines of UNIX.
I have yet to see a C compiler without the level 1 IO routines.  But
some of these compilers take liberty with the routines.

Are they interchangable? They are as interchangable as int and char *.
One is a pointer (level 2) and the other an int (not neccessarly
small/short as someone suggested).
Some libraries provide a fileno() macros that take a level 2 IO file
descriptor and convert it to the level 1 IO handle.

For system use, the most efficient way to read is to read(fd, buf,
BUFSIZ) where buf is a char array of BUFSIZ and BUFSIZ is defined in
stdio.h.  There are UNIX calls (and sometimes C library) routines to
adjust the buffering done by the process.  NOTE: There in NO NULL byte
placed on the end of the array 'buf'.

To insure portability, level 2 should be used.  One can perform
untranslated IO using the routines fread and fwrite

To read a file of structures 'struct s inst'
(teminology stolen from Pascal land) the
routines read(fd, (char *)&inst, sizeof( struct s)) should be equivalent
to fread( &inst, sizeof( struct s ), 1, stream).

Dr. Richard (Ricky) Glass



More information about the Comp.lang.c mailing list