Reputation: 185
I'm trying to write simple struct with an array to a file and then read it. It works with the array of a small size < 25 but for some reason all data after that is not initialized;
typedef struct TestStruct {
int data[30];
} TestStruct;
TestStruct *test = malloc(sizeof(TestStruct));
for (int i = 0; i < 30; i++)
{
test->data[i] = i;
}
const char *filename = "some.txt";
FILE *file = fopen(filename, "w+");
fwrite(test, sizeof(TestStruct), 1, file);
rewind(file);
TestStruct *test2 = malloc(sizeof(TestStruct));
int rc = fread(test2, sizeof(TestStruct), 1, file);
The result of this code is rc = 0
and integers after index 25 are not initialized for some reason. Can anybody explain where is the problem?
Upvotes: 1
Views: 162
Reputation: 753695
b
(for binary) in the mode string used with fopen()
, the control-Z is treated as an EOF marker when you read the data.Fix: Use "w+b"
instead of just "w+"
to deal with the problem.
Note that the return value rc = 0
from fread()
means that the read failed to read the entire structure requested (because only 26 bytes, values 0..25, were read before EOF was detected). It did its best to let you know there was a problem.
You should look at the return value from fwrite()
too, to make sure that everything you expected to be written was in fact written.
Upvotes: 3