FWRITE后立即引起文件偏移问题后,float阵列将
初始化整数array []
右行21将导致data []
来自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]);
}
如代码所示,float array1存储了两个浮点元素,并在data.txt中fwrite。数据阵列fread data.txt以获取这两个浮点元素。 结果表明:
~/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.50 2. 0.30
~/workplace/testinttofloat$ gcc main.c
~/workplace/testinttofloat$ ./a.out
1. 0.00 2. 0.00
data []
无法获得正确的结果的原因是我不使用rewind
重新定位文件偏移,因此数据
只需到达EOF即可。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论