There are four main reasons to use fopen instead of open.
fopen
provides you with buffering IO that may turn out to be a lot faster than what you're doing with open
.
fopen
does line ending translation if the file is not opened in binary mode, which can be very helpful if your program is ever ported to a non-Unix environment.
- A
FILE *
gives you the ability to use fscanf
and other stdio functions.
- Your code may someday need to be ported to some other platform that only supports ANSI C and does not support the
open
function.
In my opinion the line ending translation more often gets in your way than helps you, and the parsing of fscanf is so weak that you inevitably end up tossing it out in favor of something more useful.
And most platforms that support C have an open
function.
That leaves the buffering question. In places where you are mainly reading or writing a file sequentially, the buffering support is really helpful and a big speed improvement. But it can lead to some interesting problems in which data does not end up in the file when you expect it to be there. You have to remember to fclose
or fflush
at the appropriate times.
If you're doing seeks, the usefulness of buffering quickly goes down.
Of course, my bias is that I tend to work with sockets a whole lot, and there the fact that you really want to be doing non-blocking IO (which FILE *
totally fails to support in any reasonable way) with no buffering at all and often have complex parsing requirements really color my perceptions.