What is C ftell() and rewind()- Best C Language Course For Beginners

🚀 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 ftell() and rewind()

Free C tutorial: find your position, measure file size, and jump back to the start

Two small functions complete the random access toolkit: ftell() and rewind() in C. The first reports where the file position pointer is, the second sends it back to the start. This lecture of our free C programming course explains both with a traced program. Whether you are working through a free embedded C course or practicing embedded C programming on your own, these two functions will save you hours of debugging.

As in every part of this free C tutorial for C programming for embedded systems, the code is original and the output shown was produced by running it.

What You Will Learn in This Free C Programming Course

  • The prototype and return value of ftell()
  • How to measure file size with fseek() and ftell()
  • What rewind() does and how it differs from fseek(fp, 0L, SEEK_SET)
  • How end-of-file status behaves after rewind()
  • A complete traced program with expected output

Prerequisites for the Free C Programming Course

Finish the earlier lectures on the file position pointer, fseek() and random access records. The program here reuses the readings.dat file from the previous lecture, so run that program first.

Understanding the ftell() Function

long ftell(FILE *stream);

ftell() returns the current offset in bytes from the beginning of the file. On failure it returns -1L and sets errno. You should compare to -1L before using the value, because a negative size would make later arithmetic wrong.

ftell() while reading 20 byte records

Eventftell() returns
File just opened0
After record 120
After record 240
After record 6 (last)120

Measuring file size with ftell()

The standard trick has two steps: move to the end with fseek(fp, 0L, SEEK_END), then call ftell(). The result is the size in bytes. Move back to the start afterward if you plan to read.

Finding file size in three steps

1

Go to end

fseek(fp, 0L, SEEK_END)

2

Ask

size = ftell(fp)

3

Go back

rewind(fp)

Understanding the rewind() Function

void rewind(FILE *stream);

rewind() moves the pointer to byte 0. It returns nothing, so you cannot check for failure through a return value. According to the C standard it behaves like fseek(stream, 0L, SEEK_SET) followed by clearing the error indicator. That small difference matters, as the table shows.

Featurerewind(fp)fseek(fp, 0L, SEEK_SET)
Moves pointer to startYesYes
Return valueNone0 or non-zero
Clears end-of-file flagYesYes (on success)
Clears error flagYesNo
Lets you detect failureOnly through errno or ferrorDirectly

Which one should you use?

Use rewind() for simple programs where the file is certainly seekable and you want a clean slate. Use fseek() when you want to detect failure, for example on a stream that might be a pipe.

A Complete ftell() and rewind() Program

#include <stdio.h>

struct reading {
    int   id;
    char  sensor[12];
    float value;
};

int main(void)
{
    FILE *fp = fopen("readings.dat", "rb+");
    if (fp == NULL) { perror("fopen"); return 1; }

    printf("pointer at open        : %ld\n", ftell(fp));

    struct reading r;
    while (fread(&r, sizeof r, 1, fp) == 1) {
        printf("after record %d         : %ld\n", r.id, ftell(fp));
    }
    printf("file size via ftell    : %ld bytes\n", ftell(fp));
    printf("feof at the end        : %s\n", feof(fp) ? "yes" : "no");

    rewind(fp);
    printf("after rewind           : %ld\n", ftell(fp));
    printf("feof after rewind      : %s\n", feof(fp) ? "yes" : "no");

    if (fread(&r, sizeof r, 1, fp) == 1) {
        printf("first record again     : %s\n", r.sensor);
    }

    fseek(fp, 0L, SEEK_END);
    long end = ftell(fp);
    fseek(fp, 0L, SEEK_SET);
    printf("fseek(END)+ftell       : %ld, then back to %ld\n", end, ftell(fp));

    fclose(fp);
    return 0;
}

Build and run

gcc -std=c11 -Wall -Wextra -o tell_rewind tell_rewind.c
./make_readings
./tell_rewind

Expected output

pointer at open        : 0
after record 1         : 20
after record 2         : 40
after record 3         : 60
after record 4         : 80
after record 5         : 100
after record 6         : 120
file size via ftell    : 120 bytes
feof at the end        : yes
after rewind           : 0
feof after rewind      : no
first record again     : temp
fseek(END)+ftell       : 120, then back to 0

What the trace teaches

Look at the lines around the rewind. Before it, feof() says yes, because the loop ended by trying to read past the last record. After it, the flag is cleared and you can read again. Without the rewind, the next fread() would fail immediately. This is the exact reason rewind() is called “useful when we open a file for update” in older books: you can read the whole file, then start over without closing it.

Real-World Use Cases

  • Print the number of records before processing.
  • Read a file once to validate it, then rewind and read again to load it.
  • Log the offset of each record while building an index.
  • Reuse an open file handle for a second pass in a small utility.

Common Mistakes and Troubleshooting

Using the result of ftell() without checking for -1L. On a pipe or terminal it fails.
Storing the offset in an int. ftell() returns long. Truncating loses information on big files.
Expecting ftell() to be a character count in text mode. On systems that translate line endings the value may not equal a byte count. In text mode, pass only values from ftell() back to fseek(). Use “rb” for exact sizes.
Measuring size while the file is still being written. Buffered data may not be counted yet. Call fflush() on a writing stream first.

Best Practices, Performance and Security

  • Remember the original position before you measure, then restore it, if other code depends on it.
  • For files above 2 GiB on Linux use ftello() and fseeko() with off_t.
  • Do not trust a file size to allocate memory without an upper limit. A malicious or corrupt file can claim to be enormous.
  • If you only need the size, the POSIX stat() call avoids moving the pointer at all.

Thinking about error flags

Every stream carries two small flags: end-of-file and error. They are separate. The end-of-file flag is set when a read reaches the end, and the error flag is set when the operating system reports a failure such as a disk read error. Functions feof() and ferror() report them, and clearerr() resets both. This is why the table above says rewind() clears the error flag while a plain fseek() does not: after an I/O error, a successful seek on its own leaves the stream marked as failed. When you build a long-running program, such as a logger that runs for months, inspect ferror() after loops that read or write, so a transient failure is not silently ignored.

Practice Exercises for Your Free C Programming Course

These tasks reinforce ftell() and rewind() and prepare you for the lab. They suit anyone following this free C programming course on a Linux PC or a Raspberry Pi.

  1. Write long file_size(FILE *fp) that returns the size but leaves the file pointer exactly where it was. Hint: save the old position with ftell() first.
  2. Read the whole readings.dat file once to count records, call rewind(), and then read it again to print them.
  3. Make the program print the byte offset at which each record starts, not just where it ends.
  4. Use ferror() and clearerr() in a short test, and observe that rewind() clears the error flag.
  5. Compare your result with the shell command ls -l readings.dat or wc -c readings.dat.
FunctionNeeds a seekable fileChanges pointer
ftell()YesNo
rewind()YesYes, to 0
fseek()YesYes
feof()NoNo

Practice like this is the heart of any free C programming course, and it gives you the debugging habits used in daily embedded C programming. Verify every answer against the real program output instead of guessing.

Summary and Key Takeaways

  • ftell() returns the current offset, or -1L on error.
  • fseek(fp, 0L, SEEK_END) followed by ftell() gives the file size.
  • rewind() goes to byte 0 and clears the end-of-file and error flags.
  • fseek(fp, 0L, SEEK_SET) does the same move but returns a status.

Conclusion: Free C Programming Course Next Steps

With fseek(), ftell() and rewind() you now control the file position pointer completely. That is a solid base for this free C programming course chapter. Next we add records to the end of an existing file with append mode and then read them back to compute grades.

Frequently Asked Questions

What does ftell() return?

The current position as a long, counted in bytes from the start of the file, or -1L on error.

How do I get the size of a file with standard C?

Seek to the end with fseek(fp, 0L, SEEK_END), then call ftell(fp).

What is the difference between rewind() and fseek()?

rewind() has no return value and also clears the error flag. fseek() returns a status you can check.

Does rewind() clear end-of-file?

Yes, so you can read the file again from the start.

When does ftell() return -1?

When the stream is not seekable, or when an error occurs.

Is ftell() safe for large files?

On 32-bit systems a long may be too small. Use ftello() with off_t where available.

Free Embedded C Course: Next Topic

Next: append records to a file and generate a grade report.

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 →