Linux下getc vs fgetc

本文详细解析了getc和fgetc的区别,包括实现方式、性能影响和特殊使用场景。重点指出getc可能在多次评估流时导致意外行为,并提供安全使用建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. From the Advanced Programming in Unix Environment:

...

The difference between getc and fgetc is that getc can be implemented as a macro, whereas fgetc cannot be implemented as a macro. This means three things:

  • The argument to getc should not be an expression with side effects.
  • Since fgetc is guaranteed to be a function, we can take its address. This allows us to pass the address of fgetc as an argument to another function.
  • Calls to fgetc probably take longer than calls to getc, as it usually takes more time to call a function.

...


2.

Seems like the differences are, in 99.9% of the cases, meaningless.

One point which may make a difference - The man page says getc() may be implemented as a macro which evaluates stream more than once.

It could lead to strange behavior in some (not very useful) cases, e.g.:

FILE *my_files[10] = {...}, *f=&my_files[0];
for (i=0; i<10; i++) {
    int c = getc(f++);    // Parameter to getc has side effects!
}

If getc evaluates f++ more than once, it will advance f more than once per iteration. In comparison, fgetc is safe in such situations.



http://stackoverflow.com/questions/18480982/getc-vs-fgetc-what-are-the-major-differences

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值