目录
1.fseek函数
根据文件指针的位置和偏移量来定位文件指针。
1.1原型:
fseek函数是根据文件指针位置和偏移量来定位文件指针。
FILE *stream:是要操作的文件指针
long offset:是文件指针的偏移量
int origin: 是起始位置,是指文件指针从哪个位置开始的偏移量。
它有三种形参,分别是:SEEK_CUR(文件指针当前位置开始),SEEK_END(文件指针末尾位置开始),SEEK_SET(文件起始位置开始)。如下:
1.2使用:
#include<errno.h>
#include<string.h>
#include<stdio.h>
int main()
{
FILE* pf = fopen("text.txt", "r");
if (NULL == pf)
{
strerror(errno);
return 1;
}
//写文件
fseek(pf, 2, SEEK_SET);//以文件起始位置开始,向后偏移2Byte
int c = fgetc(pf);
printf("%c", c);
fseek(pf, 2, SEEK_CUR);//以文件指针当前位置开始,向后偏移2Byte
c = fgetc(pf);
printf("%c", c);
fseek(pf, -3, SEEK_END);//以文件末尾开始向前偏移3个byte
c = fgetc(pf);
printf("%c", c);
fclose(pf);//关闭文件
pf = NULL;
}
2.ftell函数
返回文件指针相对于起始位置的偏移量。
2.1原型
2.1使用
#include<errno.h>
#include<string.h>
#include<stdio.h>
int main()
{
FILE* pf = fopen("text.txt", "r");
if (NULL == pf)
{
strerror(errno);
return 1;
}
//写文件
fseek(pf, 2, SEEK_SET);//以文件起始位置开始,向后偏移2Byte
int c = fgetc(pf);
printf("%c\n", c);
fseek(pf, 2, SEEK_CUR);//以文件指针当前位置开始,向后偏移2Byte
c = fgetc(pf);
printf("%c\n", c);
fseek(pf, -3, SEEK_END);//以文件末尾开始向前偏移3个byte
c = fgetc(pf);
printf("%c\n", c);
printf("%d\n", ftell(pf));//返回文件指针相对于起始位置的偏移量
fclose(pf);//关闭文件
pf = NULL;
}
3.rewind函数
让文件指针的位置回到文件的起始位置。
3.1原型
3.2使用
#include<errno.h>
#include<string.h>
#include<stdio.h>
int main()
{
FILE* pf = fopen("text.txt", "r");
if (NULL == pf)
{
strerror(errno);
return 1;
}
//写文件
fseek(pf, 2, SEEK_SET);//以文件起始位置开始,向后偏移2Byte
int c = fgetc(pf);
printf("%c\n", c);
fseek(pf, 2, SEEK_CUR);//以文件指针当前位置开始,向后偏移2Byte
c = fgetc(pf);
printf("%c\n", c);
fseek(pf, -3, SEEK_END);//以文件末尾开始向前偏移3个byte
c = fgetc(pf);
printf("%c\n", c);
printf("%d\n", ftell(pf));//返回文件指针相对于起始位置的偏移量
rewind(pf);//让文件指针回到文件的起始位置
c=fgetc(pf);
printf("%c", c);
fclose(pf);//关闭文件
pf = NULL;
}