rewind file function in c
what is rewind function in c?
In C, there is no built-in function to rewind a file. However, you can use the fseek() function to set the file position indicator to the beginning of the file.
Here's an example of how you can use the fseek() function to rewind a file:
#include <stdio.h>
int main() {
FILE *fp;
char c;
fp = fopen("example.txt", "r");
if (fp == NULL) {
printf("Failed to open file.\n");
return 1;
}
// read the file
while ((c = getc(fp)) != EOF) {
printf("%c", c);
}
// rewind the file
fseek(fp, 0, SEEK_SET);
// read the file again from the beginning
while ((c = getc(fp)) != EOF) {
printf("%c", c);
}
fclose(fp);
return 0;
}
Attention: In this example, the fseek() function is called with the file pointer (fp), an offset of 0, and the SEEK_SET flag to set the file position indicator to the beginning of the file. After rewinding the file, we can read it again from the beginning. Note that the rewind() function is equivalent to fseek(fp, 0, SEEK_SET).