1

I am reading about file handling and I did find explanations like "To be precise, using this structure can, as a whole, be troublesome, so we usually use a pointer to it." I would like to know why do we always use FILE* and what is so troublesome ?

The only explanation I could find is that functions like fopen returns a pointer to FILE* so therefore we need to use as it is. Is there any situation where you would use a FILE automatic variable over pointer to it?

Cătălina Sîrbu
  • 1,253
  • 9
  • 30
  • 3
    You can't directly use the `FILE` structure because its definition is not exported from the library. It's intended to be internal to the library and opaque to client code. The only way to use it is as an opaque pointer. This is a a very standard design pattern. See: [What is an opaque pointer in C](https://stackoverflow.com/questions/7553750/what-is-an-opaque-pointer-in-c) – kaylum Nov 22 '20 at 07:09
  • Historically, the `FILE` type was not opaque, and some code (such as Perl) would look for recognized variants of the structure to 'cheat'. The `getc()` function was implemented as a macro and used internal knowledge of the structure to do so — and that's why there is also the `fgetc()` function which is assuredly a function. On macOS (Mojave), the `FILE` structure is defined in `_stdio.h` which is included from ``. But, with that said, the intention is that applications (programs) should treat the `FILE` type as opaque and only ever use pointers. _[…continued…]_ – Jonathan Leffler Nov 22 '20 at 08:13
  • 2
    _[…continuation…]_ Note that the standard (C11 [§7.21.3 Files ¶6](http://port70.net/~nsz/c/c11/n1570.html#7.21.3p6) says: _The address of the `FILE` object used to control a stream may be significant; a copy of a `FILE` object need not serve in place of the original._ Thus you can't reliably make use of `FILE` structure. – Jonathan Leffler Nov 22 '20 at 08:14

0 Answers0