#include <stdio.h>
#include <stdlib.h>
int main(void)
{
/* Prepare an array of f-p values. */
#define SIZE 5
double A[SIZE] = {1.,2.,3.,4.,5.};
/* Write array to a file. */
FILE * fp = fopen("test.bin", "wb");
fwrite(A,sizeof(double),SIZE,fp);
fclose (fp);
/* Read the f-p values into array B. */
double B[SIZE];
fp = fopen("test.bin","rb");
/* Set the file position indicator in front of third f-p value. */
if (fseek(fp,sizeof(double)*3L,SEEK_SET) != 0)
{
if (ferror(fp))
{
perror("fseek()");
fprintf(stderr,"fseek() failed in file %s at line # %d\n", __FILE__,__LINE__-5);
exit(EXIT_FAILURE);
}
}
int ret_code = fread(B,sizeof(double),1,fp); /* read one f-p value */
printf("%.1f\n", B[0]); /* print one f-p value */
fclose(fp);
return EXIT_SUCCESS;
}
结果输出
4.0
fseek参数解释
| stream | - | file stream to modify 将要改变的文件流 |
| offset | - | number of characters to shift the position relative to origin 相对于origin 位置偏移的字符个数 |
| origin | - | position to which offset is added. It can have one of the following values: SEEK_SET, SEEK_CUR, SEEK_END位置信息:开始,当前以及结尾 |

本文通过一个C语言程序示例介绍了如何使用fseek和fread函数定位并读取二进制文件中的浮点数值。该程序首先创建了一个包含浮点数的数组,并将其写入二进制文件中。接着,程序利用fseek定位到第三个浮点数的位置,并使用fread读取该数值。文章详细展示了文件指针定位和读取的具体步骤。
1082

被折叠的 条评论
为什么被折叠?



