C fopen vs open

原问题: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的四个优点)

  1. fopen provides you with buffering IO that may turn out to be a lot faster than what you're doing with open.(fopen更快)
  2. 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有结束符转换)
  3. A FILE * gives you the ability to use fscanf and other stdio functions.(fopen返回FILE*指针)
  4. 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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值