【问题标题】:How can I use fread to read in a file value by value?如何使用 fread 按值读取文件值?
【发布时间】:2017-05-11 06:20:23
【问题描述】:

我使用fwrite 存储一些数据,现在我尝试使用fread 从txt 文件中读取数据进行处理。我想单独读取这些值,但我不知道你会怎么做。这是我尝试过的:

#include <stdio.h>
#include <stdlib.h>

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

  pFile = fopen ( "myfile.txt" , "rb" );

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

  // allocate memory to contain the whole file:
  buffer = (unsigned short *) malloc (sizeof(unsigned short)*lSize);

  // copy the file into the buffer:
  result = fread (buffer,1,lSize,pFile);

  printf("%uz\n", result);

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

上面的程序编译得很好,但是当我用./a.out 运行它时,我得到一个分段错误。当我使用sudo ./a.out 运行它时,我没有遇到段错误,但没有打印出来。 知道我可以做些什么来解决它吗?

【问题讨论】:

  • 在这里做一些错误检查:pFile = fopen ( "myfile.txt" , "rb" );
  • @πάνταῥεῖ 我要检查什么?那只是打开文件。只要我的文件名正确,它应该可以正常工作。
  • 你从来没有检查过NULL的返回值!
  • 将结果打印为字符串 - 这可能是您的段错误的原因
  • @PiotrNycz 我更新了它,现在它只打印524z

标签: c++ file fread bin


【解决方案1】:

我看到的问题:

分配比需要更多的内存

之后

lSize = ftell (pFile);

lSize 设置为文件中的字符数,而不是unsigned shorts 的数量。因此,你需要

buffer = malloc(lSize);

Do I cast the result of malloc?。如果您使用的是 C++ 编译器(正如您的 C++ 标记所暗示的那样),您需要转换 malloc 的返回值。

格式说明符错误

printf("%s\n", result);

使用错误的格式说明符来打印result。你需要使用

printf("%zu\n", result);

那条线最有可能是您看到的分段错误的罪魁祸首。


逐个读取对象

你当然可以使用:

size_t count = lSize/sizeof(short);
for ( size_t i = 0; i < count; ++i )
{
   unsigned short number;
   result = fread (&number, sizeof(unsigned short), 1, pFile);        
}

你也可以使用:

size_t count = lSize/sizeof(short);
for ( size_t i = 0; i < count; ++i )
{
   result = fread (buffer+i, sizeof(unsigned short), 1, pFile);        
}

【讨论】:

  • 但是写入文件的值是 unsigned short 类型。当我按照你说的做时,我只会在屏幕上打印出一堆1z
  • fread的返回值是读取的对象数。如果一次读取一个对象,result 的值将是1。由于我建议的格式错误,您看到 1z 作为输出。它需要是"%zu" 而不是"%uz"。我修复了答案中的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-11
  • 1970-01-01
  • 2012-08-06
相关资源
最近更新 更多