c - 如何获取文件的地址?

标签 c file

<分区>

我想知道一个文件的地址。

我可以使用fopen() 打开一个文件,然后我可以使用文件指针读取它的内容。是否可以通过地址获取文件的内容?我知道它是从流而不是文件中读取的,但即使知道流的起始地址是什么也会有所帮助。

我看到了FILE结构,注意到里面有一个base指针。我已经读取了它的值,但它是 0

我做错了什么?我正在尝试的是否可行?

最佳答案

内存 (RAM) 中的内容具有可以读取和写入的地址。磁盘上的文件没有地址。您只能将文件读入内存,然后浏览它的内容。

或者您可以在流 API 中使用 fseek 来查找文件中的特定位置,然后从那里开始在内存中读取它,或者其他什么。

要用 C 语言打开和读取文件,您可以这样做:

/* fread example: read a complete file */
#include <stdio.h>
#include <stdlib.h>

int main () {
  FILE * pFile;
  long lSize;
  char * buffer;
  size_t result;

  pFile = fopen ( "myfile.bin" , "rb" );
  if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

  // obtain file size:
  fseek (pFile , 0 , SEEK_END);
  lSize = ftell (pFile);
  rewind (pFile);

  // allocate memory to contain the whole file:
  buffer = (char*) malloc (sizeof(char)*lSize);
  if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

  // copy the file into the buffer:
  result = fread (buffer,1,lSize,pFile);
  if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

  /* the whole file is now loaded in the memory buffer. */

  // terminate
  fclose (pFile);
  free (buffer);
  return 0;
}

关于c - 如何获取文件的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12512485/

相关文章:

无法读取 bash 行生成的文件

c - 访问字符串数组

file - 自动工具和版本控制

java - 从文件中读取时计算数字

xml - Powershell无法读取xml文件?

c++ - 将 Firefox 和 Chrome cookie 导入 libcurl

c - 如何删除文本文件中的某一行?

另一个 header 中的 C++ 结构函数给出 "missing type specifier"

python - 将(大量)零写入二进制文件

linux - ls -l 将用户名和组名截断为 8 个字符