fseek() vs rewind() in C

In C, both fseek() and rewind() are used to change the position of the file pointer, but they serve different purposes. fseek() provides flexible positioning anywhere in the file, while rewind() specifically moves the pointer back to the beginning.

fseek() Function

The fseek() function moves the file pointer to a specific position based on an offset and reference point.

Syntax

int fseek(FILE *stream, long int offset, int whence)

Here are the parameters −

  • stream − Pointer to the FILE object
  • offset − Number of bytes to move from the reference position
  • whence − Reference position (SEEK_SET, SEEK_CUR, SEEK_END)

Example

Create a file named "demo.txt" with sample content before running this program.
#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *f;
    f = fopen("demo.txt", "r");
    if(f == NULL) {
        printf("Can't open file or file doesn't exist.<br>");
        exit(1);
    }
    
    // Move to end of file to get size
    fseek(f, 0, SEEK_END);
    printf("File size: %ld bytes<br>", ftell(f));
    
    // Move to beginning and read first 10 characters
    fseek(f, 0, SEEK_SET);
    char buffer[11];
    fread(buffer, 1, 10, f);
    buffer[10] = '\0';
    printf("First 10 chars: %s<br>", buffer);
    
    fclose(f);
    return 0;
}

rewind() Function

The rewind() function sets the file pointer to the beginning of the file. It's equivalent to fseek(stream, 0, SEEK_SET).

Syntax

void rewind(FILE *stream)

Example

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *f;
    f = fopen("demo.txt", "r");
    if(f == NULL) {
        printf("Can't open file or file doesn't exist.<br>");
        exit(1);
    }
    
    // Read and display first line
    char line[50];
    fgets(line, sizeof(line), f);
    printf("First read: %s", line);
    
    // Rewind and read again
    rewind(f);
    fgets(line, sizeof(line), f);
    printf("After rewind: %s", line);
    
    fclose(f);
    return 0;
}

Comparison

Feature fseek() rewind()
Flexibility Can move anywhere in file Only moves to beginning
Return Value 0 on success, non-zero on failure void (no return value)
Error Handling Can check return value Cannot detect errors
Equivalent fseek(f, 0, SEEK_SET) rewind(f)

Conclusion

Use fseek() when you need flexible file positioning and error checking. Use rewind() as a convenient shortcut when you only need to return to the beginning of the file.

Updated on: 2026-03-15T09:56:30+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements