【发布时间】:2023-03-22 17:10:01
【问题描述】:
FILE 对象通常由 调用 fopen 或 tmpfile,其中 两者都返回对其中之一的引用 这些对象。
名为 FILE 的 Struct 的属性是什么,还是依赖于平台?
【问题讨论】:
-
这是一个不透明的类型。你不应该知道。唯一的访问是通过标准库中提供的函数。
标签: c file properties stdio
FILE 对象通常由 调用 fopen 或 tmpfile,其中 两者都返回对其中之一的引用 这些对象。
名为 FILE 的 Struct 的属性是什么,还是依赖于平台?
【问题讨论】:
标签: c file properties stdio
答案是平台相关。至少在 Linux 上使用 glibc,FILE 实际上是来自 _IO_FILE 的 typedef,它在 libio.h 中实现:
struct _IO_FILE {
int _flags; /* High-order word is _IO_MAGIC; rest is flags. */
#define _IO_file_flags _flags
/* The following pointers correspond to the C++ streambuf protocol. */
/* Note: Tk uses the _IO_read_ptr and _IO_read_end fields directly. */
char* _IO_read_ptr; /* Current read pointer */
char* _IO_read_end; /* End of get area. */
char* _IO_read_base; /* Start of putback+get area. */
char* _IO_write_base; /* Start of put area. */
char* _IO_write_ptr; /* Current put pointer. */
char* _IO_write_end; /* End of put area. */
char* _IO_buf_base; /* Start of reserve area. */
char* _IO_buf_end; /* End of reserve area. */
/* The following fields are used to support backing up and undo. */
char *_IO_save_base; /* Pointer to start of non-current get area. */
char *_IO_backup_base; /* Pointer to first valid character of backup area */
char *_IO_save_end; /* Pointer to end of non-current get area. */
struct _IO_marker *_markers;
struct _IO_FILE *_chain;
int _fileno;
#if 0
int _blksize;
#else
int _flags2;
#endif
_IO_off_t _old_offset; /* This used to be _offset but it's too small. */
#define __HAVE_COLUMN /* temporary */
/* 1+column number of pbase(); 0 is unknown. */
unsigned short _cur_column;
signed char _vtable_offset;
char _shortbuf[1];
/* char* _save_gptr; char* _save_egptr; */
_IO_lock_t *_lock;
#ifdef _IO_USE_OLD_IO_FILE
};
正如 Martin York 在他的 cmets 中所说,您不应该了解这种结构的内部结构。结构的这个特定定义不能保证在不同的实现中是相同的;我希望 MSVC 的文件结构会有所不同。
【讨论】:
FILE 是一个依赖于平台的类型,很可能是一个struct,它最终包含或指向至少:
char 或 wchar_t 方向;ungetc 放入流中的最后一个字符。如果我没有忘记任何事情,这就是您可以使用stdio 函数访问的所有内容,这些函数构成了使用和检查FILE 对象的唯一界面。由于FILE 是不透明的,您不应该知道如何它保存所有这些信息。
POSIX 还指定您可以使用fileno 函数/宏检索底层文件描述符。
【讨论】:
NULL 缓冲区不能实现缓冲。其余的你是对的。
来自 C 语言标准草案 n1256,第 7.19.1 节第 2 段:
声明的类型为size_t(在 7.17 中描述);
  FILE
这是一种对象类型,能够记录控制所需的所有信息 流,包括其文件位置指示符、指向其关联缓冲区的指针(如果有)、 错误指示符,记录是否发生读/写错误,end-of-file指示符,记录是否到达文件末尾;和
  fpos_t
这是一种对象类型,而不是能够记录所有信息的数组类型 需要唯一指定文件中的每个位置。
FILE 类型的确切内容取决于实现,并不意味着可以直接访问。
【讨论】:
快速回答 - 对此感到抱歉。
FILE 是句柄,而不是结构。它基本上代表您正在读取或写入的文件的锁定。
我建议阅读与 fopen 调用有关的帮助,例如,有很多在线帮助。
希望这会有所帮助。
【讨论】: