'fread a float array after a fwrite immediately will cause a file offset problem
Initial the integer array[] right line 21 will cause the failure of the data[] array fread from data.txt .
int main()
{
FILE * file0 = NULL;
file0 = fopen("data.txt", "r+");
if (file0 == NULL)
{
file0 = fopen("data.txt", "w+");
float array1[2] = {0.5, 0.3};
fwrite(array1, sizeof(float), 2, file0);
}
else
{
float array1[2] = {0.5, 0.3};
fwrite(array1, sizeof(float), 2, file0);
// int array[3] = {1,2,3};
// fwrite(array, sizeof(int), 3, file0);
}
float data[5];
int data1[5];
fread(data, sizeof(float), 2, file0);
fclose(file0);
printf(" 1. %.2f 2. %.2f\n",data[0], data[1]);
}
As the code shows, the float array1 stores two float elements and fwrite in data.txt. The data array fread the data.txt to get these two float elements. The result shows like this:
~/workplace/testinttofloat$ gcc main.c
~/workplace/testinttofloat$ ./a.out
1. 0.50 2. 0.30
The result will show like this:
~/workplace/testinttofloat$ gcc main.c
~/workplace/testinttofloat$ ./a.out
1. 0.50 2. 0.30
~/workplace/testinttofloat$ gcc main.c
~/workplace/testinttofloat$ ./a.out
1. 0.00 2. 0.00
The reason why data[] cannot get the correct results is that I didn't use rewind to reposition the file offset, so the data just reach the EOF.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
