文件读写问题与读写指针定位问题
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
FILE *p;
int i=0,j=0;
long int a=0;
if((p=fopen("zs.txt","w"))==NULL) //以写的形式打开文件
{
printf("Can not open source file");
exit(0);
}
srand((unsigned) time(NULL));
for(i=0;i<5;i++)
{
fprintf(p,"%d ",(rand()%5+1));
} //产生1——5的5个随机数,将随机数写入文件
fclose(p);
if((p=fopen("zs.txt","r+"))==NULL) //以读写方式打开文件
{
printf("Can not open source file");
exit(0);
}
for(j=0;j<5;j++)
{
fscanf(p,"%d",&i);
fseek(p,a,SEEK_SET);
fprintf(p,"%d ",i+1);
a=ftell(p);
} //读入一个整数,把它加一,然后重新覆盖写入
fclose(p);
return 0;
}
本程序希望达到效果为使产生的五个随机数的文件,每个数加一。
但是本程序出现问题,从第三个数开始fscanf无法读入新数,每次文件结果后四个都是一样的。
不知道是为什么,希望高手给讲解一下啊。