rewind() in C
The rewind() function in C resets the file pointer to the beginning of a file. It is a part of the standard input/output library and provides a simple way to reposition the file pointer without specifying an offset.
Syntax
void rewind(FILE *stream);
Parameters
- stream: A pointer to the file object whose pointer needs to be reset.
The rewind() function does not return a value and does not report any errors. It is equivalent to calling fseek(file, 0, SEEK_SET)
.
Example: Using rewind()
#include <stdio.h>
int main()
{
FILE *file = fopen("example.txt", "w+");
if (file == NULL) {
printf("Error opening file\n");
return 1;
}
// Write data to the file
fputs("Hello, World!", file);
// Reset the file pointer to the beginning
rewind(file);
// Read and print the data
char buffer[50];
if (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("Data: %s\n", buffer);
}
fclose(file);
return 0;
}
Output:
Data: Hello, World!
#include <stdio.h>
int main()
{
FILE *file = fopen("example.txt", "w+");
if (file == NULL) {
printf("Error opening file\n");
return 1;
}
// Write data to the file
fputs("Hello, World!", file);
// Reset the file pointer to the beginning
rewind(file);
// Read and print the data
char buffer[50];
if (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("Data: %s\n", buffer);
}
fclose(file);
return 0;
}
Output:
Data: Hello, World!
Key Points
- rewind() resets the file pointer to the beginning of the file.
- It is a simple alternative to
fseek(file, 0, SEEK_SET)
. - Unlike fseek(), it does not return any value or provide error reporting.
- Commonly used to reread a file from the beginning or to restart writing.