rewind() in C
0 288
The rewind() function in C is used to reset the file position indicator for a file stream back to the beginning of the file.
It sets the file pointer to the start, making the file ready for a subsequent read or write operation from the beginning.
Syntax of rewind():
void rewind(FILE *stream);
stream: Pointer to the FILE object that identifies the file stream.
Example:
#include<stdio.h>int main() { FILE *fp; char ch; // Open a file named "example.txt" in read mode fp = fopen("example.txt", "r"); // Check if the file opened successfully if (fp != NULL) { ch = fgetc(fp); printf("First character: %c\n", ch); rewind(fp); ch = fgetc(fp); printf("First character after rewind: %c\n", ch); // Close the file fclose(fp); } else { printf("Error opening file.\n"); } return 0; }
Output:
Error opening file.
Diagram:
We open a file named "example.txt" in read mode.
We read and print the first character from the file.
We then use rewind(fp); to reset the file pointer to the beginning of the file.
After rewinding, we read and print the first character again to verify that the file pointer has been reset.
Finally, we close the file using fclose(fp).
The diagram illustrates the file positions before and after the rewind() operation.
After rewind(), the file pointer is positioned back at byte 0 (| symbol in the diagram).
Share:
Comments
Waiting for your comments