Link to home
Start Free TrialLog in
Avatar of AtTheMike93
AtTheMike93

asked on

When to use fopen vs open

When should I use fopen vs open?

Why does the standard have two sets of functions to handle files?
SOLUTION
Avatar of sunnycoder
sunnycoder
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Beware of the SunOS and Solaris bug with fopen()

As grg99 mentions, fopen() uses open() to open the file and stores the returned
file descriptor in the FILE structure.  However, the file descriptor returned from
open() is an integer, but the SUN version of the FILE structure only reserves a
byte to hold the file descripter.  That means if your program has 255 file descriptors
opened by any means (stdio, open(), fopen(), popen(), socket(), mmap(), etc)
using fopen() to open the 256'th file (or any file after that) will cause the file
descriptor to be truncated when it is stored in the FILE structure.   Using that
FILE structure to perform I/O in the future will access the WRONG file.

IIRC, HP/UX had that same bug in the past, but later fixed it.

Avatar of Dale_M
Dale_M

The answers to these questions are simple:

1) use fopen unless you know you have a good reason for using open

2) open came first, and then the designers of C realized there's a better way of doing things for most cases
Avatar of AtTheMike93

ASKER

Thank you all for your comments.

Since I consider the buffering to be the major difference between the two, I assigned stefan73 comment as the accpeted answer.