C rewind()
Syntax
void rewind(FILE *stream);
Example
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE* fp;
char ch;
fp = fopen("example.txt", "r");
if (fp == NULL) {
printf("Cannot open file.\n");
exit(1);
}
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}
rewind(fp);
printf("\n\nAfter rewind:\n\n");
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}
fclose(fp);
return 0;
}
Output
This is an example file.
It shows how the rewind() function works.
This text will be printed twice.
After rewind:
This is an example file.
It shows how the rewind() function works.
This text will be printed twice.
Explanation
The rewind()
function in C is used to set the file position indicator to the beginning of the file. This is useful when you want to read a file more than once, or if you want to read from a file after writing to it.
Use
The rewind()
function is commonly used when reading from files in C. It sets the file position indicator to the beginning of the file so that the file can be read again from the start. This is useful when implementing file reading operations in a loop or function.
Important Points
- The
rewind()
function takes a file pointer as its argument. - The
rewind()
function sets the file position indicator to the beginning of the file. - The
rewind()
function is useful when you want to read a file more than once. - Use
fseek()
if you want to set the file position indicator to an exact position in the file.
Summary
The rewind()
function is a simple yet powerful function in C that allows you to set the file position indicator to the beginning of a file. This is useful when you want to read from a file more than once, or when implementing loops or functions that read from a file. With a basic understanding of its syntax and use cases, rewind()
can greatly enhance the functionality of your file input/output operations in C.