I have a txfile.txt file which has the following data:
2716 16253
7721 35149
972 2614

I am trying to read the first integer into a variable using this code:

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

int main()
        int num_cust[1];
        int result; 
        FILE *fp;
        if( (fp = fopen("tsfile.txt", "r")) == NULL)
		perror("Error opening file\n");

	result = fread(&num_cust[0], sizeof(int), 1, fp);
	if(result != 1)
		printf("read error\n");
	printf("num_cust = %d\n", num_cust[0]);


I expected num_cust to be 3 (the first integer in the file). But the printout shows it to be 856306231. Wondering what can be wrong.

you are reading the binary representation of an integer instead of the decimal representation of an integer. result = fread(&num_cust[0], sizeof(int), 1, fp); reads however many bytes the size of an integer is (on most computers, that is 4 bytes.) So assuming a 4 byte integer, the function would read the bytes represented by the characters "3\n27" into the variable result.

You should use the fscanf function for getting input that would be a decimal number like fscanf(fp, "%d", &result);

commented: thanks for solving the problem. +0