Im trying to write and read an array of ints in a binary file. The two functions look like this, more or less.
savefunction
int numbers[6]={0, 2, 3, 3, 0, 1};
FILE *file;
if(file=fopen(filename, "wb")==NULL)
{
printf("Something went wrong reading %s\n", filename);
return 0;
}
else
{
int i;
for(i=0; i<6; i++)
fprintf(file, "%d", numbers[i]);
}
fclose(file);
loadfunction
FILE *saved_data;
int errors=0;
if((saved_data=fopen(filename, "rb"))==NULL)
errors++;
else
{
fread(first, sizeof(int), 1, saved_data);
fread(second, sizeof(int), 1, saved_data);
fread(third, sizeof(int), 1, saved_data);
fread(fourth, sizeof(int), 1, saved_data);
fread(fifth, sizeof(int), 1, saved_data);
fread(sixt, sizeof(int), 1, saved_data);
}
fclose(saved_data);
Now when I debug the program the debugger tells me that the first element is the following
(gdb) print first
$1 = (int *) 0x7fff5fbff968
(gdb) print *first
$2 = 858993200
I can’t understand this. The file when opening with editor says 023301
The complementary function of
freadisfwrite, notfprintf. What you’re doing withfprintfis putting the integers into the file as text, not as binary.Also, make sure you pass a pointer to
fread, not an integer. You don’t show the declarations offirst,second, and so on, but if you’ve declared something likethen you’ll need to use code like
rather than
Since your integers are already in an array, you can just write the array in one go with
and avoid the
forloop altogether.