rewind () 函數,
fseek (fp, offset, seek_set) 函數,
ftell (fp) 函數。
程序附錄:
/* Description: the test of function
* rewind()
* fseek(fp, offset, seek_set)
* ftell(fp)
* Time: 2012.10.11
* Author: essencelite
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main()
{
FILE * fp;
char *ps = "fseek(), fsetpos() return 0, and ftell() returns the current offset. \
Otherwise, -1 is returned and errno is set to indicate the error.";
int length = strlen(ps);
/* creat re.txt and copy content to re.txt */
fp = fopen("re.txt", "w");
if (fp == NULL) {
perror("fopen re.txt error\n");
exit(EXIT_FAILURE);
}
int ret = fwrite(ps, 1, length, fp);
printf("ret = %d \n",ret);
fclose(fp);
/*---------------------------------------rewind()-------------------------------------------
* description: set the fp to the start of the file
*-----------------------------------------------------------------------------------------*/
/* test the rewind() function */
int i = 0;
char ch = 0;
fp = fopen("re.txt", "r");
if (fp == NULL) {
perror("fopen error\n");
exit(EXIT_FAILURE);
}
for(i = 0; i < 10; i++) {
ch = fgetc(fp);
printf("_%c_", ch);
}
printf("\n");
rewind(fp);
ch = fgetc(fp);
printf("ch = %c \n", ch);
fclose(fp);
/*--------------------------------fseek(fp, offset, seek_set)-------------------------------
* description: set the fp to point to the station (seek_set+offset);
* from "seek_set" to "seek_set + offset", fp point to the (seek_set+offset);
* example: fseek(fp, 10L, 8) which means:from 8 to 18; fp point to the 18;
* the offset can be negative;
* parameters: set = 0, stand the start of file;
* cur, stand current station;
* END, stand end of the file;
*-----------------------------------------------------------------------------------------*/
/* test the fseek(fp, offset, seek_set) function */
i = 0;
ch = 0;
fp = fopen("re.txt", "r");
if (fp == NULL) {
perror("fopen error\n");
exit(EXIT_FAILURE);
}
fseek(fp, 10L, 0);
/* -------------------------------------ftell(fp)------------------------------------------
*description: location the current station of the fp
*---------------------------------------------------------------------------------------*/
/* test the ftell() function */
long tell = ftell(fp);
printf("after 10 offset form ,the current fp station, tell = %d \n", tell);
printf("\n");
fclose(fp);
return 0;
}