What are C fseek() Function Explained- Free Online C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

PREV_LEC | NEXT_LEC

C fseek() Function Explained

Free C tutorial: SEEK_SET, SEEK_CUR and SEEK_END with a program you can run

The fseek() function in C moves the file position pointer to any byte you choose. It is the main tool for random access, and it appears in nearly every real file-handling program. This lecture belongs to our free C programming course and is written for learners of embedded C programming who want a clear, tested explanation instead of a copy of a textbook page.

If you are following this free embedded C course to prepare for C programming for embedded systems jobs, pay attention to the return value rules and the end-of-file behavior. Interviewers like to ask about both.

What You Will Learn in This Free C Programming Course

  • The prototype of fseek() and what each argument means
  • The three origin constants and their values
  • How positive and negative displacement behave
  • What fseek() returns, and what happens when you seek past the end
  • A complete tested program with expected output

Prerequisites for the Free C Programming Course

Read the previous lecture on the file position pointer first. You should be comfortable with fopen(), fgetc() and ftell().

The fseek() Function Prototype

int fseek(FILE *stream, long offset, int whence);
ArgumentMeaning
streamThe open file whose pointer you want to move
offsetA signed long: number of bytes to move. Positive goes forward, negative goes backward
whenceThe reference point the offset is measured from

The third argument is often called origin. It is one of three macros from stdio.h.

MacroTypical valueOffset is measured from
SEEK_SET0The beginning of the file
SEEK_CUR1The current pointer position
SEEK_END2The end of the file

Always use the macro names

The numbers 0, 1 and 2 are the usual values, but the C standard only promises the macro names. Writing SEEK_SET is portable and self-explaining. Also note the spelling: it is SEEK_CUR, not SEEK_CURRENT. Old books sometimes get this wrong, and the wrong name will not compile.

How the fseek() Function Works Step by Step

fseek() origin and offset on a 26 byte file

CallStarts fromLands on offsetByte read next
fseek(fp, 10L, SEEK_SET)010K
fseek(fp, 5L, SEEK_CUR)1116Q
fseek(fp, -5L, SEEK_CUR)1712M
fseek(fp, -3L, SEEK_END)2623X
fseek(fp, 0L, SEEK_END)2626nothing (end)

Three reference points for the same file

0

SEEK_SET

Count forward from byte 0. Offsets should be zero or positive.

N

SEEK_CUR

Count from where the pointer is now. Positive or negative.

E

SEEK_END

Count from the end. Use zero or negative values to stay inside the file.

Why the offset is a long

The offset type is long so a file larger than what an int can count can still be addressed. Write constants with an L suffix, such as 10L, so the compiler passes a long. On many embedded and 32-bit systems a long is 32 bits, which limits you to about 2 GiB. For bigger files on Linux look at fseeko() and off_t.

Complete fseek() Demo Program

#include <stdio.h>
#include <string.h>
#include <errno.h>

static void peek(FILE *fp, const char *label)
{
    int c = fgetc(fp);
    printf("%-26s -> '%c'  (pointer now %ld)\n", label, c, ftell(fp));
}

int main(void)
{
    FILE *fp = fopen("alpha26.txt", "wb");
    if (fp == NULL) { perror("fopen"); return 1; }
    fputs("ABCDEFGHIJKLMNOPQRSTUVWXYZ", fp);
    fclose(fp);

    fp = fopen("alpha26.txt", "rb");
    if (fp == NULL) { perror("fopen"); return 1; }

    fseek(fp, 10L, SEEK_SET);
    peek(fp, "SEEK_SET, +10");

    fseek(fp, 5L, SEEK_CUR);
    peek(fp, "SEEK_CUR, +5");

    fseek(fp, -5L, SEEK_CUR);
    peek(fp, "SEEK_CUR, -5");

    fseek(fp, -3L, SEEK_END);
    peek(fp, "SEEK_END, -3");

    fseek(fp, 0L, SEEK_END);
    printf("%-26s -> pointer %ld (file size)\n", "SEEK_END, 0", ftell(fp));

    int rc = fseek(fp, -1L, SEEK_SET);
    printf("%-26s -> returned %d, errno: %s\n",
           "SEEK_SET, -1", rc, strerror(errno));

    rc = fseek(fp, 100L, SEEK_SET);
    printf("%-26s -> returned %d, pointer %ld, fgetc is %s\n",
           "SEEK_SET, +100", rc, ftell(fp),
           fgetc(fp) == EOF ? "EOF" : "data");

    fclose(fp);
    return 0;
}

Build and run

gcc -std=c11 -Wall -Wextra -o fseek_demo fseek_demo.c
./fseek_demo

Expected output

SEEK_SET, +10              -> 'K'  (pointer now 11)
SEEK_CUR, +5               -> 'Q'  (pointer now 17)
SEEK_CUR, -5               -> 'M'  (pointer now 13)
SEEK_END, -3               -> 'X'  (pointer now 24)
SEEK_END, 0                -> pointer 26 (file size)
SEEK_SET, -1               -> returned -1, errno: Invalid argument
SEEK_SET, +100             -> returned 0, pointer 100, fgetc is EOF

Reading the output

Notice that after every peek() the pointer is one more than the offset you seeked to, because reading one byte moved it forward. This is why the second call lands on Q and not on P: the pointer was at 11, not 10, when the relative seek started. Tracking this extra step is the most common source of off-by-one errors.

Return Value and Error Handling for fseek()

SituationResult
Seek succeededReturns 0
Target would be before byte 0Returns non-zero, errno set (EINVAL on Linux)
Seek past the end of a regular fileUsually returns 0; a later read gives EOF
Stream not seekable (pipe, terminal)Returns non-zero

Always test the return value in real code. A failed seek leaves the pointer where it was, so a following fread() would silently read the wrong data.

Real-World Uses of the fseek() Function

  • Jump to a fixed header field in a binary firmware image.
  • Read the last record of a log by seeking back one record from the end.
  • Find a file’s size: seek to the end and call ftell().
  • Skip over padding or unknown sections in a binary format.

Common Mistakes

Forgetting the L suffix or a cast. Passing an int expression that overflows before the call gives a wrong offset. Compute offsets as long.
Using SEEK_CUR after a read and forgetting the pointer already moved. Write the arithmetic on paper first.
Relative seeks in text mode. The standard only guarantees SEEK_SET with values from ftell(), or zero offsets with other origins, for text streams. Use binary mode for arbitrary offsets.
Ignoring the return value. A failed seek is invisible unless you check.

Best Practices and Performance

  • Use the macro names, never bare 0, 1, 2.
  • Seek only when you need to. Each fseek() discards the stream read buffer, so seeking before every tiny read makes a program slow. Read in blocks when you can.
  • Wrap seek-and-read in a helper function that returns an error code.
  • Check that the target offset is inside the file before seeking when the offset comes from user input or from file contents. Offsets taken from untrusted data are a classic security bug.

Practice Exercises for Your Free C Programming Course

This free C programming course works best when you experiment. Try these small tasks with the demo file from this lecture, and write the expected result on paper first.

  1. Write the call that lands on the letter T of the 26 letter file using SEEK_SET, then again using SEEK_END.
  2. Starting at offset 4, which call lands on offset 20 using SEEK_CUR? Check your answer with ftell().
  3. Write a function int goto_byte(FILE *fp, long pos) that returns 0 on success and -1 on failure, and refuses negative positions before calling fseek().
  4. Seek 5 bytes before the end and read 5 bytes with fread(). This is the pattern for printing the tail of a log.
GoalCall
First bytefseek(fp, 0L, SEEK_SET)
Last bytefseek(fp, -1L, SEEK_END)
Skip 4 bytes aheadfseek(fp, 4L, SEEK_CUR)
Go back 4 bytesfseek(fp, -4L, SEEK_CUR)

Finishing these tasks in a free C programming course gives you the same confidence you need when reading a binary header in real embedded C programming work.

Summary and Key Takeaways

  • fseek(fp, offset, origin) moves the pointer; it returns 0 on success.
  • Origins: SEEK_SET start, SEEK_CUR here, SEEK_END end.
  • Negative offsets move backward but must not pass byte 0.
  • Seeking past the end is allowed; reading there gives EOF.

Conclusion: Free C Programming Course Next Steps

The fseek() function is small, but it opens up everything that makes file handling useful in a free C programming course for embedded learners: patching images, reading records by number, and jumping to the tail of a log. In the next lecture you will combine fseek() with fread() to pull out any record from a binary file by its number.

Frequently Asked Questions

What does fseek() return?

0 on success, a non-zero value on failure.

What is the difference between SEEK_SET and SEEK_CUR?

SEEK_SET measures from the start of the file; SEEK_CUR measures from the current position.

Can fseek() go backward?

Yes, with a negative offset, as long as the result is not before byte 0.

What happens if I seek past the end of the file?

On regular files the call normally succeeds, and a read from there returns EOF.

Why does fseek() need a long?

So that large files can be addressed. Use fseeko() with off_t when files exceed the long range.

Is SEEK_CURRENT a valid name?

No. The correct macro is SEEK_CUR.

Keep Learning Embedded C Programming

Next lecture: read any record of a binary file by number.

PREV_LEC | NEXT_LEC

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →