If we write:
//in main
FILE *p = fopen("filename", "anymode");
My question is: to what is p
pointing?
Join Stack Overflow to learn, share knowledge, and build your career.
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.
FILE
. What you get back from fopen()
is a FILE *
, which points at a FILE
structure. The structure that is pointed at contains all the information that the library needs to manage I/O to the file. One consequence is that it seldom contains the file name; that isn't needed once the file is open. The FILE
structure is not the buffer; the buffer is an array of characters. The FILE
structure contains a pointer to the buffer, either supplied by the system or provided by the user via setvbuf()
or setbuf()
. [...continued...]
– Jonathan Leffler
Mar 5 '14 at 1:56
FILE *
avoids single-character operations when it can).
– Jonathan Leffler
Mar 5 '14 at 2:00
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
.
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.