0

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?

  • 3
    `*file` is an object of type `FILE` which you are not supposed to know anything about. It might be a struct or a union or who knows what. You can't safely cast it to any particular type. If you want to know what it is, you'll have to inspect your C library's source code, or reverse engineer it. – Nate Eldredge Oct 25 '20 at 23:29

1 Answers1

0

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

kill -9
  • 159
  • 1
  • 9
  • I thought that if I would dereferencing a pointer to a struct that then the first data field would get accessed, because the alignment of its members. But this seems not to be the case. But printing the members of the struct, as you guessed works. Thanks. – Nico Schumann Oct 25 '20 at 23:45
  • `struct _IO_FILE` is just an implementation detail in a specific C library. Not all standard libraries use that name and the content will also be different. It may not even be a struct but a pointer to some internal structure – phuclv Oct 26 '20 at 04:34