fread不会对缓冲区进行更改(C)

时间:2015-03-12 11:54:21

标签: c fopen fread

我正在尝试一点点恐惧,然后我开始练习我必须解密二进制文件," imagen.png"。

在下面的代码中,我尝试存储" 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]);
}

1 个答案:

答案 0 :(得分: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