1.fseek的用法:
fseek函数的原型是int fseek(FILE*stream,long offset,int fromwhere);函数设置文件指针stream的位置.如果执行成功,stream将以fromwhere为基准,偏移offset个字节的位置,offset为正数向右偏移,为负数向左偏移.
int main()
{
FILE* ps = fopen("test.txt", "r");
int ch = fgetc(ps);
printf("%c ", ch);
ch = fgetc(ps);
printf("%c ", ch);
fseek(ps, 2, SEEK_CUR);
ch=getc(ps);
printf("%c ", ch);
}
2.ftell的用法:
ftell函数原型为long int ftell(FILE*stream),用于获取文件位置指针当前位置相对于文件首的偏移字节数.
nt main()
{
FILE* ps = fopen("test.txt", "r");
int ch = fgetc(ps);
printf("%c ", ch);
ch = fgetc(ps);
printf("%c ", ch);
fseek(ps, 2, SEEK_CUR);
ch=getc(ps);
printf("%c ", ch);
int ret = ftell(ps);
printf("%d ", ret);
}
```![在这里插入图片描述](https://img-blog.csdnimg.cn/464d9ddafc2345f4854e648002ef6854.png)
3.rewind的用法:函数原型void rewind(FILE*filepointer),将读写位置指针重制到文件开头.
int main()
{
FILE* ps = fopen(“test.txt”, “r”);
int ch = fgetc(ps);
printf("%c “, ch);
ch = fgetc(ps);
printf(”%c “, ch);
fseek(ps, 2, SEEK_CUR);
ch=getc(ps);
printf(”%c “, ch);
int ret = ftell(ps);
printf(”%d “, ret);
rewind(ps);
ch = fgetc(ps);
printf(”%c ", ch);
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/9ef7d626aa4547e79be4cc09f848bd43.png)
4.ferror和feof函数
feof:当文件读取结束时,判断是不是遇到文件末尾才结束的.如果没有到文件末尾,返回0,到了文件末尾,返回非0,
int main()
{
FILE* ps = fopen(“test.txt”, “r”);
int ch = fgetc(ps);
printf(“%c “, ch);
ch = fgetc(ps);
printf(”%c “, ch);
fseek(ps, 2, SEEK_CUR);
ch=getc(ps);
printf(”%c “, ch);
int ret = ftell(ps);
printf(”%d “, ret);
rewind(ps);
ch = fgetc(ps);
printf(”%c\n”, ch);
if (feof(ps))
{
printf(“到了文件末尾\n”);
}
else
{
printf(“没到文件末尾\n”);
}
}
ferror:判断函数是否是遇到错误才读取结束的,如果是,则返回非0,否则返回1.
int main()
{
FILE* ps = fopen(“test.txt”, “r”);
int ch = fgetc(ps);
printf(“%c “, ch);
ch = fgetc(ps);
printf(”%c “, ch);
fseek(ps, 2, SEEK_CUR);
ch=getc(ps);
printf(”%c “, ch);
int ret = ftell(ps);
printf(”%d “, ret);
rewind(ps);
ch = fgetc(ps);
printf(”%c\n”, ch);
if (ferror(ps))
{
printf(“遇到错误\n”);
}
else
{
printf(“没遇到错误\n”);
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/03c31146beac4e86adce4ba5d2a6979a.png)