【问题标题】:What is represented by the content of FILE*FILE* 的内容代表什么
【发布时间】:2016-07-29 19:54:08
【问题描述】:

我有这个程序

#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);
}

我知道34代表文件描述符,0、1、2分别是stdinstdoutstderr。显然fopen 不使用文件描述符。

FILE* 的值代表什么? fopen 如果没有文件描述符怎么办?

【问题讨论】:

  • C 标准仅声明 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;。实现需要提供有关此的任何详细信息,实际上我认为某些编译器将FILE 实现为“不透明类型”,这意味着您无法知道其中的内容。
  • @Lundin 这是一个很好的答案,我认为你应该这样发布。
  • @Myst 不,我不认为它回答了关于文件描述符的问题。我对 Linux 中 stdio.h 的内部了解不多,所以我不会发布答案。
  • @Myst 他不想因为这个问题有数百个重复。
  • @MartinJames Dupes,真的吗?不,这不是为什么。对我来说似乎是一个足够明智的问题。

标签: c linux unix file-descriptor


【解决方案1】:

FILE* 的值代表什么?

它是一个指向FILE结构的指针,对于glibc它的定义是here。其中,除其他外,包含文件描述符。您可以使用 POSIX fileno 函数从 FILE* 获取文件描述符。

有关更多详细信息,您可以查看Interaction of File Descriptors and Standard I/O Streams

【讨论】:

    猜你喜欢
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 2019-07-10
    • 1970-01-01
    相关资源
    最近更新 更多