【C语言】文本操作函数fseek、ftell、rewind
一、fseek
int fseek ( FILE * stream, long int offset, int origin );
重新定位文件指针的位置,使其指向以origin
为基准、偏移offset
字节的位置。
成功返回0
,失败返回非零值(通常为-1
)。
origin有如下三种:分别是从开头、中间、结尾开始
int main()
{FILE* pf = fopen("test.txt", "r");if (pf == NULL){perror(pf);}else{//abcdefint ch = fgetc(pf);printf("%c\n", ch);//ach = fgetc(pf);printf("%c\n", ch);//bch = fgetc(pf);printf("%c\n", ch);//c//想要跳回到b进行读取,三种方法//1.fseek(pf, 1, SEEK_SET);//2.fseek(pf, -2, SEEK_CUR);fseek(pf, -5, SEEK_END);ch = fgetc(pf);printf("%c\n", ch);//b}return 0;
}
二、ftell
long int ftell ( FILE * stream );
得到的是返回文件指针相对于起始位置的偏移量,数字的大小代表当前光标距离文件起始处的字节数。
返回值的类型是long
int main()
{FILE* pf = fopen("test.txt", "r");if (pf == NULL){perror(pf);}else{//abcdefint ch = fgetc(pf);printf("%c\n", ch);//aprintf("%d\n", ftell(pf));//偏移量1ch = fgetc(pf);printf("%c\n", ch);//bprintf("%d\n", ftell(pf));//偏移量2ch = fgetc(pf);printf("%c\n", ch);//cprintf("%d\n", ftell(pf));//偏移量3}return 0;
}
三、rewind
void rewind ( FILE * stream );
使文件读写指针指向文件开始位置
int main()
{FILE* pf = fopen("test.txt", "r");if (pf == NULL){perror(pf);}else{//abcdefint ch = fgetc(pf);printf("%c\n", ch);//ach = fgetc(pf);printf("%c\n", ch);//bch = fgetc(pf);printf("%c\n", ch);//crewind(pf);ch = fgetc(pf);printf("%c\n", ch);//a}return 0;
}