I have a txfile.txt file which has the following data:
3
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");
		exit(1);
	}

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

}

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.

Recommended Answers

All 3 Replies

I was able to solve the problem by using c++ - iostream and fstream functions as described in this thread:
http://www.daniweb.com/forums/thread318066.html
Thanks to the forum for this.

But I would also appreciate if someone can point out the error in my c code. thanks.

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

yea that solved the problem. thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.