The fseek() and rewind() functions are used to reposition the file pointer in a file stream. While both can move the pointer to the beginning of a file, they differ in flexibility, error handling, and usage.
- fseek() moves the file pointer to any specified location.
- rewind() resets the file pointer to the beginning of the file.
- Both functions are declared in the <stdio.h> header file.
fseek()
The fseek() function repositions the file pointer relative to the beginning, current position, or end of a file.
- Supports random file access.
- Can move forward or backward.
- Returns a status value for error checking.
Example: The following program moves the file pointer back to the beginning using fseek().
#include <stdio.h>
int main()
{
FILE *fp = fopen("test.txt", "r");
if (fp == NULL)
return 1;
// Move to the beginning of the file
if (fseek(fp, 0, SEEK_SET) == 0)
printf("File pointer repositioned successfully.");
fclose(fp);
return 0;
}
Output
File pointer repositioned successfully.Explanation: The fseek() function moves the file pointer to the beginning of the file. Its return value can be checked to determine whether the operation was successful.
rewind()
The rewind() function resets the file pointer to the beginning of the file.
- Moves the pointer to the beginning only.
- Clears the file error and EOF indicators.
- Does not provide a return value.
Example: The following example resets the file pointer to the beginning using rewind().
#include <stdio.h>
int main()
{
FILE *fp = fopen("test.txt", "r");
if (fp == NULL)
return 1;
// Reset the file pointer
rewind(fp);
printf("File pointer reset to the beginning.");
fclose(fp);
return 0;
}
Output
File pointer reset to the beginning.Explanation: The rewind() function resets the file pointer to the beginning of the file. Unlike fseek(), it does not return a value, so its success cannot be checked directly.
fseek() Vs rewind()
| Feature | fseek() | rewind() |
|---|---|---|
| Functionality | Moves the file pointer to a specific location. | Resets the file pointer to the beginning of the file. |
| Arguments | Takes three arguments: file pointer, offset, and whence. | Takes only the file pointer. |
| Flexibility | More flexible as it allows moving the file pointer relative to the beginning, current position, or end. | Less flexible, only resets the pointer to the beginning. |
| Error Checking | Returns an integer (0 for success, non-zero for failure). | Does not return anything (does not provide error status directly). |
| Use Case | Used when you need to move the pointer to a specific location (e.g., for random access). | Used for resetting the file pointer (e.g., for reading the file from the beginning). |