c语言要改变文件读取位置,会用到rewind语句和fseek语句
rewind语法格式是
rewind(fp)将fp指向的文件读写指针重新指向文件开头
rewind代码示例如下
cpp
#include<stdio.h>
int main()
{
FILE *fp1,*fp2;
char buf[10];
int a;
fp1=fopen("aaa.txt","r");
fp2=fopen("hhh.dat","w");
a=fread(buf,1,10,fp1);
while(a!=0)
{
fwrite(buf,1,a,fp2);
a=fread(buf,1,10,fp1);
}
fputc('\n',fp2);
fputc('\n',fp2);
rewind(fp1);
a=fread(buf,1,10,fp1);
while(a!=0)
{
fwrite(buf,1,a,fp2);
a=fread(buf,1,10,fp1);
}
fclose(fp1);
fclose(fp2);
return 0;
}
fseek语句语法格式如下
fseek(文件位置,位移量,起始点)
起始点
0表示文件开始的位置
1表示当前读写的位置
2表示文件末尾位置
cpp
#include<stdio.h>
int main()
{
FILE *fp1,*fp2;
char buf[10];
int a;
fp1=fopen("aaa.txt","r");
fp2=fopen("ooo.txt","w");
fseek(fp1,10,0);
a=fread(buf,1,10,fp1);
while(a!=0)
{
fwrite(buf,1,a,fp2);
//fseek(fp1,10,1);
a=fread(buf,1,10,fp1);
}
fclose(fp1);
fclose(fp2);
return 0;
}