getc() vs fgetc() - What are the major differences?

前端 未结 3 635
慢半拍i
慢半拍i 2020-12-23 13:33

Everywhere I see \"it is practically identical\", or something similar...

From The GNU C Programming Tutorial :

There is another function in t

相关标签:
3条回答
  • 2020-12-23 14:06

    There are essentially the same (or similar enough to not bother). You should look at their implementation: GNU libc and MUSL libc are free software implementations. And they now could be implemented as inline functions (which are as fast as macros).

    And I won't bother that much. In real life, I/O is mostly constrained by hardware (e.g. the time to access the disk).

    0 讨论(0)
  • 2020-12-23 14:09

    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.

    ...

    0 讨论(0)
  • 2020-12-23 14:22

    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.

    0 讨论(0)
提交回复
热议问题