【问题标题】:fread won't do changes to buffer (C)fread 不会更改缓冲区 (C)
【发布时间】:2015-03-12 11:54:21
【问题描述】:

在我动手做一个必须解密二进制文件“imagen.png”的练习之前,我正在用 fread 做一些实验。

在以下代码中,我尝试将“imagen.png”的前 40 个字节存储在数组 v[] 中。问题是 v[] 中没有进行任何更改。之前,前两个值是5,剩下的8个是垃圾。之后,同样适用。

我做错了什么?

unsigned int v[10];
v[0] = 5;
v[1] = 5;

//Here I display the content of the array v[]
int j;
for (j = 0; j < 10; j++){
    printf("v-->%d\n", v[j]);
}

FILE *fp = NULL;
fp = fopen("C:\\imagen.png", "rb");

//Here I read the first 10 blocks of 4 bytes into the array v[]
if (fp != NULL){
    fread(v, sizeof(unsigned int), 10, fp);
}else{
    printf("error in opening file!\n");
}
fclose(fp);

//I display the content of array v[] again
for (j = 0; j < 10; j++){
    printf("v-->%d\n",v[j]);
}

【问题讨论】:

  • fread 返回了什么值?
  • “打开文件出错!”是规范的无用错误消息。而且您将其打印到错误的流中。试试char *path;...fp = fopen(path, "rb"); if(fp == NULL) {perror(path);...} 确保在 fopen 和 perror 之间没有调用可能会修改 errno。
  • 我刚刚检查过:fread 返回 10。
  • 注意:考虑更容易维护:fread(v, sizeof v[0], sizeof v/sizeof v[0], fp)

标签: c fopen fread


【解决方案1】:

fopen 之后的测试应该是

int cnt= -1;
FILE *fp =  fopen("C:\\imagen.png", "rb");
if (fp == NULL){
  perror("fopen imagen.png");
  exit(EXIT_FAILURE);
} else {   
  cnt = fread(v, sizeof(unsigned int), 10, fp);
  if (cnt<0) {
    perror("fread failed");
    exit(EXIT_FAILURE);
  }
  /// use cnt cleverly ....
}

fread 正在返回一个计数。你应该测试一下。所以使用cnt

【讨论】:

    猜你喜欢
    • 2013-01-17
    • 1970-01-01
    • 2021-10-24
    • 2023-03-11
    • 2012-01-31
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多