C PROGRAMMING PROGRAM • FILE HANDLING

Read a File Position Using fseek()

Learn how to read a file position using fseek() using a clear C program.

Advancedfseek()SEEK_ENDRandom access

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Last character = E

COMPLETE C PROGRAM

Complete C implementation

random-access-fseek.c
Open in compiler
#include <stdio.h>

int main(void)
{
    FILE *file = fopen("letters.txt", "wb");
    if (file == NULL) return 1;
    fputs("ABCDE", file);
    fclose(file);
    file = fopen("letters.txt", "rb");
    if (file == NULL) return 1;
    if (fseek(file, -1L, SEEK_END) != 0) { fclose(file); return 1; }
    int character = fgetc(file);
    fclose(file);
    if (character == EOF) return 1;
    printf("Last character = %c\n", character);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Last character = E
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Move the file-position indicator relative to the end and read from that exact byte.
  3. Display the computed result.

Move the file-position indicator relative to the end and read from that exact byte.

EFFICIENCY

Time and space complexity

Time complexity

O(1)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.