What is represented by the content of FILE*

笑着哭i 提交于 2019-12-14 03:57:08

问题


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?


回答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.



来源:https://stackoverflow.com/questions/36501498/what-is-represented-by-the-content-of-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!