Reputation: 2183
If we write:
//in main
FILE *p = fopen("filename", "anymode");
My question is: to what is p
pointing?
Upvotes: 10
Views: 27105
Reputation: 7922
p
is a pointer to the stored FILE
object from fopen()
.
It is really a pointer to the stream to the file, through which operations can be performed. However, the actual inner workings of the object are abstracted away.
From http://www.cplusplus.com/reference/cstdio/fopen/ :
fopen
FILE * fopen ( const char * filename, const char * mode );
Opens the file whose name is specified in the parameter filename and associates it with a stream that can be identified in future operations by the FILE pointer returned.
Upvotes: 1
Reputation: 753495
The file pointer p
is pointing a structure handled by the C library that manages I/O functionality for the named file in the given open mode.
You can't tell, a priori, whether what it points at is statically allocated memory or dynamically allocated memory; you don't need to know. You treat it as an opaque pointer.
Note that the standard says:
ISO/IEC 9899:2011 7.21.3 Files
The address of the
FILE
object used to control a stream may be significant; a copy of aFILE
object need not serve in place of the original.
This says (roughly): Don't futz around with the pointer; pass it to the functions that need it and otherwise leave well alone.
Upvotes: 19
Reputation: 881113
p
points to a memory location holding a FILE
structure. That's all you really need to know, the contents of that structure are entirely implementation-specific.
If it's implemented correctly in terms of encapsulation (i.e., as an opaque structure), you shouldn't even be able to find out what it contains.
All you should be doing with it (unless you're the implementer of the standard library) is receive it from fopen
and pass it to other functions requiring a FILE *
, such as fwrite
, fread
and fclose
.
Upvotes: 3