user6607311 user6607311 - 2 months ago 19
C Question

Error while reading integers using fread in C

I have written the following C code to read 5 integers from an input file:

#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *fp;
unsigned *ch;
unsigned i,n=5;

ch=(unsigned*)malloc(n*sizeof(unsigned));
fp=fopen("input","r");
fread(ch ,sizeof(unsigned),n,fp);
fclose(fp);
for(i=0;i<n;i++)
printf("\n%u ",ch[i]);
free(ch);
return 0;
}


The input file is:

1 2 3 4 58


But the output I am getting is:

540155953
540287027
14389
0
0


Please help me out.

Answer

fread and fwrite are used for binary files. Data in a binary file is interpreted as bytes as they would appear in memory as opposed to text files which can be read by humans. Using the hexdump command on linux, we can see the hexadecimal values for your input file

$ hexdump -C input
00000000  31 20 32 20 33 20 34 20  35 38 0a         

Using the hex column of the ASCII table, you can see that 0x31 is the 1 character, 0x20 is a space character, etc. But because fread interprets the data in the file as binary, it will read 4 bytes for each unsigned int. You can check that 0x20322031 (the first 4 bytes in the file in reverse order) is equal to 540155953.

If you want to generate the data in the file in binary and subsequently read it, you can use

#include<stdio.h>
#include<stdlib.h>
int main(){
  FILE *fp;
  unsigned *ch;
  unsigned i,n=5;

  unsigned int arr[] = {1,2,3,4,58};

  ch=(unsigned*)malloc(n*sizeof(unsigned));
  fp=fopen("input","w+");
  fwrite(arr,sizeof(unsigned),n,fp); /* write binary */
  fseek(fp, SEEK_SET, 0); /* move file cursor back to the start of the file */
  fread(ch ,sizeof(unsigned),n,fp); /* read binary */
  fclose(fp);
  for(i=0;i<n;i++)
    printf("\n%u ",ch[i]);
  free(ch);  
  return 0;
}

and examine the file called input to see the differences.

As noted in the comments, you can fscanf with a %u specifier to grab unsigned ints if you want to interpret the data as a text file.

Comments