有三种方法可以定位流。
fseek函数中的whence的值与lseek函数相同:SEEK_SET表示从文件的起始位置开始,SEEK_CUR表示从当前文件位置#include <stdio.h> long ftell(FILE* fp); //如果成功返回当前文件位置指示,出错则返回-1. int fseek(FILE* fp, long offset, int whence); //如果成功则返回0,出错则返回非0值。 void rewind(FILE* fp); //定位到流的开头。
#include <stdio.h> int main(void){ FILE* fp; int result; int c; if((fp = fopen("a.txt", "r+")) == NULL){ result = -1; perror("fopen"); goto FINALLY; } printf("position:%ld\n",ftell(fp)); if((c = fgetc(fp)) != -1){ printf("read c:%c\n",c); } if((c = fgetc(fp)) != -1){ printf("read c:%c\n",c); } printf("position:%ld\n",ftell(fp)); if(fseek(fp, 3, SEEK_CUR) != 0){ result = -1; perror("fseek"); goto FINALLY; } printf("position:%ld\n",ftell(fp)); rewind(fp); printf("position:%ld\n",ftell(fp)); FINALLY: if(fp != NULL){ fclose(fp); } return result; }运行结果:
#include <stdio.h> off_t ftello(FILE* fp); //成功则返回当前文件的位置指示,出错则返回-1 int fseeko(FILE* fp, off_t offset, int whence); //成功则返回0,出错返回非0值实践:
#include <stdio.h> int main(void){ FILE* fp; int result; int c; if((fp = fopen("a.txt", "r+")) == NULL){ result = -1; perror("fopen"); goto FINALLY; } printf("position:%ld\n",ftell(fp)); if((c = fgetc(fp)) != -1){ printf("read c:%c\n",c); } if((c = fgetc(fp)) != -1){ printf("read c:%c\n",c); } printf("position:%ld\n",ftello(fp)); if(fseeko(fp, 3, SEEK_CUR) != 0){ result = -1; perror("fseek"); goto FINALLY; } printf("position:%ld\n",ftell(fp)); FINALLY: if(fp != NULL){ fclose(fp); } return result; }运行结果:
#include <stdio.h> int fgetpos(FILE* restrict fp, fpos_t* restrict pos); int fsetpos(FILE* fp, fpos_t *pos);
#include <stdio.h> int main(void){ FILE* fp; int result; int c; fpos_t pos1,pos2; if((fp = fopen("a.txt", "r+")) == NULL){ result = -1; perror("fopen"); goto FINALLY; } if((c = fgetc(fp)) != -1){ printf("read c:%c\n",c); } if((c = fgetc(fp)) != -1){ printf("read c:%c\n",c); } if(fgetpos(fp,&pos1) != 0){ result = -1; perror("fgetpos"); goto FINALLY; } printf("position:%ld\n",pos1); if((c = fgetc(fp)) != -1){ printf("read c:%c\n",c); } if((c = fgetc(fp)) != -1){ printf("read c:%c\n",c); } if(fgetpos(fp,&pos2) != 0){ result = -1; perror("fgetpos"); goto FINALLY; } printf("position:%ld\n",pos2); if(fsetpos(fp, &pos1) != 0){ result = -1; perror("fsetpos"); goto FINALLY; } if(fgetpos(fp,&pos2) != 0){ result = -1; perror("fgetpos"); goto FINALLY; } printf("position:%ld\n",pos2); FINALLY: if(fp != NULL){ fclose(fp); } return result; }运行结果: