文件的随机读写
实现随机文件的读写的关键是要按要求移动位置指针,这称为文件的定位
文件定位函数 rewind 和 fseek
移动文件内部位置指针的函数主要有 rewind() 和 fseek()
rewind()用来将位置指针移动到文件的开头,前面以多次使用过, 他的原型为:
void rewind(FILE *fp);
fseek()用来将位置指针指到任意的位置,他的原型为:
int fseek(FILE *fp, long offset, int origin); 文件指针, 偏移量, 起始位置
起始点 常量名 常量值
文件开头 SEEK_SET 0
文件位置 SEEK_CUP 1
文件末尾 SEEK_END 2
文件的随机读写
在移动文件指针之后, 就可以用前面介绍的任何一种读写函数进行读写
#include <stdio.h>
#include <stdlib.h>
#define N 3
struct student
{
char name[30];//姓名
int number; //学号
int age; //年龄
float score; //成绩
} boys[N], boy, *pboys;
int main(void)
{
FILE *fp;//文件指针
pboys = boys;
if((fp = fopen("d:\\demo.txt", "wb+")) == NULL)
{
printf("Cannot open file, press any key to exit it!\y");
system("pause");
exit(1);
}
else
{
printf("input data : \n");
for(int i = 0; i<N; i++, pboys++)
{
scanf("%s %d %d %f", pboys->name, &pboys->number, &pboys->age, &pboys->score);
}
fwrite(boys, sizeof(struct student), N, fp);
fseek(fp, sizeof(struct student), SEEK_SET);
fread(&boy, sizeof(struct student), 1, fp);
printf("%s %d %d %f\n", boy.name, boy.number, boy.age, boy.score);
fclose(fp);
}
return 0;
}
结果: