Lập trình C - C rewind()
Hàm rewind()
Hàm rewind() sẽ đặt lại vị trí con trỏ nội bộ của tập tin về đầu tập tin.
Cú pháp:
void rewind(FILE *stream)
Ví dụ: trong tập tin file.txt có nội dung sau:
this is a simple text
Code chương trình sau:
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char c;
clrscr();
fp=fopen("file.txt","r");
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
rewind(fp);//Di chuyển con trỏ đến đầu tập tin
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
fclose(fp);
getch();
}
Kết quả:
this is a simple textthis is a simple text
Như đã thấy. Hàm rewind() di chuyển con trỏ lên đầu tập tin để print chuỗi "this is simple text" 2 lần. Nếu không gọi hàm rewind thì chỉ print ""this is simple text" một lần