Course contentsShow
← C
Lesson 734 of 1,21910. Input and OutputFree lesson

The SEEK_SET, SEEK_CUR, SEEK_END constants

The SEEK_SET, SEEK_CUR, SEEK_END constants

What you'll learn: How to use pre-defined constants to tell C exactly where to start moving the file cursor.

When you use the fseek() function, you are essentially picking up a "bookmark" and moving it to a new location in a file. However, for the computer to move that bookmark, it needs a reference point. Does "move 10 steps" mean 10 steps from the beginning, or 10 steps from where you are standing right now?

To answer this, C provides three standard constants that act as anchors for your movement.

The Three Anchors

Think of a file like a physical scroll. To find a specific word, you need to know where to start measuring from:

  1. SEEK_SET (The Beginning): This refers to the very start of the file. If you use SEEK_SET with an offset of 0, you go to the very first character. If you use an offset of 10, you go to the 10th character from the start. It is the most common way to "reset" or jump to a specific known position.
  2. SEEK_CUR (Current Position): This refers to wherever the cursor is sitting right now. If you just read 50 bytes and want to skip the next 5, you use SEEK_CUR. It’s like saying, "From where I am standing, take two steps forward."
  3. SEEK_END (The End): This refers to the very end of the file. This is most commonly used with a negative offset to "back up" from the end, or with an offset of 0 to prepare the file for appending new data at the very bottom.

Seeing it in Code

Here is how these constants look inside the fseek() function:

#include <stdio.h>

int main() {
    FILE *fptr = fopen("example.txt", "r");

    // 1. Jump to the 10th byte from the start
    fseek(fptr, 10, SEEK_SET);

    // 2. Skip forward 5 bytes from where we are now
    fseek(fptr, 5, SEEK_CUR);

    // 3. Jump to the very end of the file
    fseek(fptr, 0, SEEK_END);

    // 4. Back up 20 bytes from the end
    fseek(fptr, -20, SEEK_END);

    fclose(fptr);
    return 0;
}

Why use constants?

You might wonder why we don't just use numbers like 0, 1, or 2. Using these named constants makes your code "readable." When another programmer sees SEEK_END, they instantly know you are navigating relative to the end of the file, making your intentions clear without needing a comment.

Key takeaway

SEEK_SET, SEEK_CUR, and SEEK_END define your starting point: the beginning, your current spot, or the end of the file.