【问题标题】:File's pyshical memory location or variable?文件物理内存位置或变量?
【发布时间】:2020-08-16 22:00:11
【问题描述】:

我刚开始学习指针和打开文件。那么,当我使用FILE 数据类型打开现有文件进行读取时,指针指向文件内存位置还是变量内存位置?

#include <stdio.h> // I/O

int main(int argc, char const *argv[])
{
    FILE *fpointer = fopen("employees", "r");
    fclose(fpointer);

    return 0;
} 

如果指针指向文件的内存位置,当我打印指针时,输出的将是内存中的确切文件位置?

printf("memory address: %p\n", fpointer);
// i.e 0x55a5ca11a2a0

【问题讨论】:

  • 文件不在您的进程内存中。它位于某些存储设备(例如磁盘)上。文件指针指向一个包含缓冲信息的结构。读取文件时,它以存储在缓冲区中的块的形式读取。当需要更多时,会进行 I/O 调用以读取更多文件。
  • @TomKarzes The file isn't in your process memory 是的,我知道。但我认为该变量保存文件位置,因为为了打开它,他需要它的位置。很高兴知道!
  • FILE 是一个用于描述的结构。该结构包含操作系统需要了解的有关该文件的所有信息。比如磁盘上的物理位置、当前文件指针(通常是文件的当前(在 linux 中)inode、输入和输出缓冲区等。调用fopen() 返回一个指向该结构实例的指针。那些结构实例保存在一个数组中,调用 open() 会返回该数组的索引。

标签: c pointers


【解决方案1】:

它不保存“文件位置”,它保存一个文件句柄,这是操作系统在打开文件时发出的东西,允许您从中读取和/或写入。

FILE 结构不仅包括句柄,它还为缓冲区预留了少量内存,以提高性能。

您可能可以在头文件中找到FILE 工作原理的确切定义。

这是一个示例定义:

struct _IO_FILE
{
  int _flags;           /* High-order word is _IO_MAGIC; rest is flags. */

  /* The following pointers correspond to the C++ streambuf protocol. */
  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;
  int _flags2;
  __off_t _old_offset; /* This used to be _offset but it's too small.  */

  /* 1+column number of pbase(); 0 is unknown. */
  unsigned short _cur_column;
  signed char _vtable_offset;
  char _shortbuf[1];

  _IO_lock_t *_lock;
#ifdef _IO_USE_OLD_IO_FILE
};

【讨论】:

    猜你喜欢
    • 2020-10-30
    • 2015-11-09
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多