2

I have this program

#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <fcntl.h>

int main(void)
{
    FILE* f = fopen("/Users/user/a.cc", "rb");
    printf("%i\n", f);  // 1976385616
    printf("%i\n", *f);  // 1976385768

    int sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
    printf("%i\n", sockfd);  // 4

    fclose(f);
    close(sockfd);

    int fd = open("/Users/user/a.cc", O_TRUNC | O_WRONLY, 0);
    printf("%i\n", (int) fd); // 3
    close(fd);
}

I know that 3 and 4 represents the file descriptors with 0, 1, 2 being stdin, stdout and stderr respectively. Obviously fopen doesn't use a file descriptor.

What does the value of FILE* represent? How does fopen if not with file descriptors?

hgiesel
  • 5,430
  • 2
  • 29
  • 56
  • 7
    The C standard only states that `FILE`: `...is an object type 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;`. An implementation need to provide any details about this, in fact I think some compilers implement `FILE` as an "opaque type", meaning you can't know what's inside it. – Lundin Apr 08 '16 at 14:01
  • 1
    @Lundin This is a good answer, I think you should post it as such. – Myst Apr 08 '16 at 14:32
  • @Myst No I don't think it answers the question, which was about file descriptors. I don't know much of the internals of stdio.h in Linux, so I'll refrain from posting an answer. – Lundin Apr 08 '16 at 14:35
  • @Myst he prolly does not want to because of the hundreds of dups of this question. – Martin James Apr 08 '16 at 14:36
  • @MartinJames Dupes, really? No that's not why. Seems like a sensible enough question to me. – Lundin Apr 08 '16 at 14:37
  • @Lundin yes, there are dups:( No, I'm not going hunting either:) – Martin James Apr 08 '16 at 14:39
  • [What do FILE struct members mean exactly in C?](http://stackoverflow.com/q/29768610/995714), [What exactly is the FILE keyword in C?](http://stackoverflow.com/q/5672746/995714), [I Wanna know the Internal Members of struct FILE, the latest ones](http://stackoverflow.com/q/17209087/995714) – phuclv Apr 08 '16 at 16:41

1 Answers1

1

What does the value of FILE* represent?

It is a pointer to FILE structure, for glibc its definition is here. Which, among other things, contains the file descriptor. You can get the file descriptor from FILE* using POSIX fileno function.

For more details you may like having a look into Interaction of File Descriptors and Standard I/O Streams.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271