有了fseek()函数,便可把文件看作是数组,在fopen()打开的文件中直接移动到任意字节处。我们创建一个程序reverse.c 演示fseek()和ftell()的用法。注意,fseek()有3个参数,返回int类型的值;ftell()函数返回一个long类型的值,表示文件中的当前位置。
/* reverse.c -- displays a file in reverse order */#include #include #define CNTL_Z '032' /* eof marker in DOS text files */#define SLEN 81int main(void){ char file[SLEN]; char ch; FILE *fp; long count, last; puts("Enter the name of the file to be processed:"); scanf("%80s", file); if ((fp = fopen(file,"rb")) == NULL) { /* read-only mode */ printf("reverse can't open %sn", file); exit(EXIT_FAILURE); } fseek(fp, 0L, SEEK_END); /* go to end of file */ last = ftell(fp); for (count = 1L; count <= last; count++) { fseek(fp, -count, SEEK_END); /* go backward */