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.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Last character = E
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Last character = E
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Move the file-position indicator relative to the end and read from that exact byte.
- 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.
