What is the difference between using FILE and FILE * variable address in C?

Given the following short example

FILE *p = fopen("foo.txt", "r");
FILE f = *p;

int i;
fscanf(p, "%i", &i); // works just fine
fscanf(&f, "%i", &i); // segmentation fault

      

I did a bit of familiarization with FILE

, FILE *

as well as the actual type of structure _IO_FILE

, but I'm not quite clear what is causing the segmentation fault in the second call fscanf

.

So, aside from p

and &f

containing different addresses, and if it's not related (which I think it is), what is the difference between &f

and p

in this context?

+3


source to share


2 answers


The C standard (C99 7.19.3 / 6, C11 7.21.3 / 6) says:

The address of the FILE object used for flow control can be significant; a copy of the FILE object should not be used in place of the original.



So you have been warned.

+6


source


You can think of sensu lato FILE*

as an opaque pointer , you should never try to do what you do.

From cppreference.com :



C streams are type objects std::FILE

that can only be accessed and manipulated with type pointers std::FILE*

(Note: while it might be possible to create a local type object std::FILE

by dereferencing and copying a valid one std::FILE*

, using the address of such a copy in I / O functions is behavior is undefined).

0


source







All Articles