简体   繁体   中英

fread won't do changes to buffer (C)

I am experimenting a little with fread before I put my hands on an exercise where I have to decrypt a binary file, "imagen.png".

In the following code, I attempt to store the first 40 bytes of "imagen.png" in an array v[]. The problem is that no changes are made in v[]. Before, the two first values are 5, and the remaining 8 are garbage. After, the same applies.

What am I doing wrong?

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]);
}

Your test after fopen should be

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 is returning a count. You should test it. So use cnt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM