Use %d
instead of %ld
to print an int
And take a look to Why is “while ( !feof (file) )” always wrong?
A struct
haves a fixed size, you can use ftell
to get the size of the file and then divide using the size of the struct
in order to get the number of records, also, always check the result of those functions.
Something like:
FILE *file;
long size;
size_t count, records;
file = fopen("myfile", "rb");
if (file == NULL) {
perror("fopen");
return 0;
}
if (fseek(file, 0, SEEK_END) == -1) {
perror("fseek");
return 0;
}
size = ftell(file);
if (size == -1) {
perror("ftell");
return 0;
}
if (fseek(file, 0, SEEK_SET) == -1) {
perror("fseek");
return 0;
}
records = size / sizeof(x);
for (count = 0; count < records; count++) {
if (fread(&x, sizeof(x), 1, file) == 1) {
printf("\n\nID:%d",x.ID); /* %d instead of %ld */
} else {
break;
}
}
But notice that you are always writing to the same variable on the stack.
EDIT:
How do you store the struct
in the file?
I'm not storing it, a program is.
If it is not yours (you don't build the file using the same struct
) then you can't know which is the sizeof(x)
inside the file, read about structure padding and packing.