#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位置信息:开始,当前以及结尾 |