原问题:https://stackoverflow.com/questions/1658476/c-fopen-vs-open
Is there any reason (other than syntactic ones) that you'd want to use
FILE *fopen(const char *path, const char *mode);
instead of
int open(const char *pathname, int flags, mode_t mode);
when using C in a Linux environment?
Reasons:
There are four main reasons to use fopen
instead of open
.(fopen的四个优点)
fopen
provides you with buffering IO that may turn out to be a lot faster than what you're doing withopen
.(fopen更快)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 (though the world appears to be converging on LF-only (except IETF text-based networking protocols like SMTP and HTTP and such)).(fopen有结束符转换)- A
FILE *
gives you the ability to usefscanf
and other stdio functions.(fopen返回FILE*指针) - Your code may someday need to be ported to some other platform that only supports ANSI C and does not support the
open
function.(fopen有利于跨平台)
(fopen的缺点)
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.(只要支持C,就会支持open)
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.
(虽然可以减少内核态和用户态转换,但是必须记得fclose fflush去同步)
If you're doing seeks (aka(also know as) fsetpos
or fseek
the second of which is slightly trickier to use in a standards compliant way), 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.(这位老外更喜欢用socket)