fwrite和fread函数用于二进制文本读写,按数据块读文件
而fprintf和fscanf函数用于文本文件,以ASCII码存储的文件读写
fseek函数好像也主要用于二进制文件(第二段代码如果我是文本文件,不改变fseek函数语句,会出现错误)
//将内容先以二进制形式存到文件中
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student
{
long id;
char name[10];
int year;
}STUDENT;
int main()
{
FILE *fp;
STUDENT stu[3];
int i,f=100310121;
fp=fopen("score2.txt","wb");
for(i=0;i<3;i++){
stu[i].id=f;
f++;
}
strcpy(stu[0].name,"王刚");
strcpy(stu[1].name,"李小明");
strcpy(stu[2].name,"王力宏");
int x=1991;
for(i=0;i<3;i++){
stu[i].year=x;
x++;
}
fwrite(stu,sizeof(STUDENT),3,fp);
fclose(fp);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
//读取第k条记录
typedef struct student
{
long id;
char name[10];
int year;
}STUDENT;
void searchfile(char filename[],long k);
int main(){
long k;
printf("input the searching record number:");
scanf("%ld",&k);
searchfile("score2.txt",k);
return 0;
}
void searchfile(char filename[],long k){
FILE *fp;
STUDENT stu;
if((fp=fopen(filename,"rb"))==NULL){
printf("failure to open %s!\n",filename);
}
fseek(fp,(k-1)*sizeof(STUDENT),0);//第k条记录,偏移k-1位
printf("record number = %d\n",ftell(fp)/sizeof(STUDENT)+1);//ftell()返回的是字节偏移量,偏移量为它再除以结构体变量所占字节数,当前位置为偏移量+1
fread(&stu,sizeof(STUDENT),1,fp);
printf("%10ld%8s%6d\n",stu.id,stu.name,stu.year);
printf("record number = %d\n",ftell(fp)/sizeof(STUDENT)+1);//fscanf()读取完一条记录后,文件位置指针指向下一条记录
fclose(fp);
}