紧接上一篇文章,上一篇是对文件进行二进制的读写操作,这篇文章对文本进行读写操作,需要注意,当用fprintf输入数据到文件时,如果有一个数据是int a=10022,如果二进制输入int型占用4个字节,但是用fprintf(格式化文本)输入,却占用5个字节,这一点需要注意,所以在用fseek定位时,可以在任何位置定位,无需定位到每个数据类型的第一个,也就是说,如果文件中保存的是int a=10022,那么定位第0个字节并且输出就可以输出1,第一个字节就可输出0,第二个字节也可输出0第三个就是2第四个就是2,如果是以二进制形式写入文件的,那么必须用fseek定位到第0个字节,输出一个int型的数据才能正确输出10022。下面我们看代码和执行结果。
//格式化写文件
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct{
int sno;
char name[10];
}student;
int main ()
{
FILE * fp;
int i;
student stu[5];
stu[0].sno=201701;strcpy(stu[0].name,"li");
stu[1].sno=201702;strcpy(stu[1].name,"wang");
stu[2].sno=201703;strcpy(stu[2].name,"zhang");
stu[3].sno=201704;strcpy(stu[3].name,"zhao");
stu[4].sno=201705;strcpy(stu[4].name,"huang");
if((fp = fopen ("xiaoke.txt","w"))==NULL)
{
printf("cant open the file");
exit(0);
}
for(i=0;i<5;i++)
{
fprintf(fp,"%d%s\n",stu[i].sno,stu[i].name);
}
fclose (fp);
return 0;
}
//格式化读文件操作
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct{
int sno;
char name[10];
}student;
int main () {
FILE * fp;
student stu;
long a;
char dingwei;
if((fp=fopen("xiaoke.txt","r"))==NULL) //rb代表按照二进制的方式进行读
{
printf("cant open the file");
exit(0);
}
//fscanf函数读取返回值为读取的个数
while(fscanf(fp,"%d%s",&stu.sno,stu.name) == 2)
{
printf("%d %s\n",stu.sno,stu.name);
}
//文件中的空格是两个字节,但是两个字节输出时都是空格
printf("输入您要定位的字节数\n");
scanf("%ld",&a);
fseek(fp,a,0);
dingwei=fgetc(fp);
printf("%c\n",dingwei);
return 0;
}