So I have declared a pointer *f
of type FILE
and now I say that that pointer is equal to fopen("text.txt", "r")
. So since a pointer stores an address, is fopen
giving back the address of a file?
FILE *f;
f = fopen("text.txt","r");
CodePudding user response:
is fopen giving back the adress of a file?
No. There is no such thing as "address of a file".
What fopen
returns is a pointer to dynamically allocated opaque structure FILE
, which describes how to get the contents of the file. This description is opaque in a sense that it provides no useful info to you. But routines such as fgets()
, fread()
, etc. know how to use that info to get the actual file contents.
fclose
deallocates this structure, so if you have matching fopen
and fclose
there are no memory leaks (from these functions).
CodePudding user response:
The function fopen
is returning the address of an object of type FILE
. According to §7.21.1 ¶2 of the ISO C11 standard, this object must be capable of
recording all the information needed to control a stream, including its file position indicator, a pointer to its associated buffer (if any), an error indicator that records whether a read/write error has occurred, and an end-of-file indicator that records whether the end of the file has been reached;
The exact size and contents of this object may differ from compiler to compiler and is of no interest to the average programmer. All that the average programmer must know is that they must pass the pointer returned by fopen
to other I/O functions provided by the C standard library.
CodePudding user response:
The standard does not specify how FILE
should be defined. The only thing it says is what result you will get when you pass an object of that type to various functions. This means that this type may be different in various implementations. This is ONE way that is used:
typedef struct _iobuf
{
char* _ptr;
int _cnt;
char* _base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char* _tmpfname;
} FILE;
It comes from MinGW32.
CodePudding user response:
Yes, it's giving back the address of a FILE
object. Now that type is opaque. That is, you are meant to not know the actual contents of the data structure being referenced and hence must never dereference the pointer (happily, the compiler will not let you get away with this).