//随机读写数据,读写操作由文件内部指针指向决定
#include"stdio.h"
#include"stdlib.h"
//声明一个数据块
struct student
{
char name[10];
int age;
float score;
};//该结构体占用20个字节
void main()
{
FILE *fp;
student s1[]={{"wangyan",40,89.0},{"王玚",6,99.1}};//初始化两个学生对象信息
student s2[2],*p1,*p2;
p1=s1;
p2=s2;
fp=fopen("testfseek.txt","wt+");
if(fp==NULL)
{
printf("文件打开失败");
getchar();
exit(1);
}
else
{
printf("文件打开成功!\n");
fwrite(p1,sizeof(struct student),2,fp);//
if(feof(fp)>1) printf("文件已结尾\n");//如果feof(fp)返回值大于1,说明文件内部指针指向结尾
else printf("文件不在结尾处\n");
fseek(fp,sizeof(struct student),SEEK_SET);
//将文件内部指针定位到从文件头起始后移sizeof(struct student)字节处
int i=ftell(fp);
printf("当前文件内部指针离文件头字节数:%d\n",i);
fread(p2,sizeof(struct student),1,fp);
printf("读到的内容是:\n");
printf("%s %d %f\n",p2->name,p2->age,p2->score);
fseek(fp,0,0);//文件内部指针重新定位到文件头,偏移0个字节
char ch=fgetc(fp);
printf("重新读到的字符是:\n");
while(ch!=EOF)//如果没有这个循环体 if(feof(fp)>1) 表达式就不会为真
{
printf("%c",ch);
ch=fgetc(fp);
}
printf("\n");
if(feof(fp)>1) printf("文件已结尾\n");//如果feof(fp)返回值大于1,说明文件内部指针指向结尾
else printf("文件不在结尾处\n");
if(ferror(fp)==0)printf("文件没有出错!\n");
else printf("文件出错!\n");
}
if(NULL==fclose(fp))printf("文件关闭成功\n");
else printf("文件关闭失败\n");
}
/*
fseek(FILE *,int(位移字节数),0(文件内部指针位移起始处))
0 SEEK_SET:文件头
1 SEEK_CUR:文件当前位置
2 SEEK_END:文件尾

////////////----------GKXW--////////2015年11月24日23:01:00///////////
*/
|