c - 读取文件内容到内存,32位操作系统和64位操作系统结果不同

标签 c fread

我在下面编写了一个函数来将文件的内容读取到内存中。 它在我的本地计算机(Ubuntu 32位)上运行良好,但在服务器(CentOS 64位)上产生错误的结果。

错误情况: 对于 40 字节的文件,内容如下,在 64 位操作系统上,它给出了错误的结果。

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

代码:

char* file_get_contents(const char *filename) {
  FILE *stream = NULL;
  char *content = NULL;
  size_t ret;
  struct stat st;

  if ((stream = fopen(filename,"r")) == NULL) {
    fprintf(stderr, "Failed to open file %s\n", filename);
    exit(1002);
  }

  if(stat(filename, &st) < 0) {
    fprintf(stderr, "Failed to stat file %s\n", filename);
    exit(1002);
  }

  content = malloc(st.st_size);
  ret = fread(content, 1, st.st_size, stream);

  if (ret != st.st_size) {
    fprintf(stderr, "Failed to read file %s\n", filename);
    exit(1002);
  }

  fclose(stream);
  return content;
}

最佳答案

调用者无法正确使用您的file_get_contents。它返回一个 char * 但不返回它的长度,也不返回一个字符串(即它不是以 null 结尾的。)。

只要您正在阅读文本,就可以执行以下操作:

  content = malloc(st.st_size + 1); // + 1 here for the nul terminator
  ret = fread(content, 1, st.st_size, stream);

  if (ret != st.st_size) {
    fprintf(stderr, "Failed to read file %s\n", filename);
    exit(1002);
  }
  content[st.st_size] = 0; //nul terminate

关于c - 读取文件内容到内存,32位操作系统和64位操作系统结果不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11984300/

相关文章:

c - 处理进程间大文件的 mmap 和 fread

c - 关于什么时候我们应该使用关键字 'volatile'?

c++ - 阻塞模式的原理是什么?

c - 如何将 C 函数放入某个地址范围

c - 解释使用链表实现的栈的输出

c - fseek() 和 ftell() 在循环中失败

c++ - 数组中相隔 8 个或更多位置的两个元素的最大乘积

c - fread() c 中的一个结构体

c - .dat 文件中的 fread()

c - Fread 中止 6 错误