ccastingfilehandle

How I get the value of a FILE* instance?


I'm trying to examine the data that fopen() returns. But I fail in reading out the data to which the pointer points.

#include <stdio.h>

int main( void )
{
    FILE * file = fopen("file.txt");
    printf( "%#llx,\n", (long long) (*file) );
}

with gcc, I get this error at compiling:

6:5: error: aggregate value used where an integer was expected
    6 |     printf( "%#llx,\n", (long long) (*file) );
      |     ^~~~~~

clang throws

6:37: error: operand of type 'FILE' (aka 'struct _IO_FILE') where arithmetic or pointer type is required
    printf( "%#llx,\n", (long long) (*file) );
                                    ^~~~~~~

So why fails the cast, and how to fix this?


Solution

  • You cannot print out the value like that. A FILE* is a pointer. You can print out the address the pointer is pointing to, but I don’t think you want that. The address the pointer is pointing to holds a struct with the type struct _IO_FILE.

    You cannot print the struct out. However you can look up the declaration of this struct and print out members of the struct. If you’d like to see the declarations of this struct, refer to this