How to Use fseek in C: Syntax, Example, and Tips
In C,
fseek moves the file pointer to a specific location in a file. You use it by passing a file pointer, an offset, and a position indicator like SEEK_SET, SEEK_CUR, or SEEK_END. This lets you read or write at any point in the file.Syntax
The fseek function has this syntax:
int fseek(FILE *stream, long offset, int whence);
- stream: The file pointer returned by
fopen. - offset: Number of bytes to move the pointer.
- whence: Starting point for offset. It can be
SEEK_SET(start of file),SEEK_CUR(current position), orSEEK_END(end of file).
The function returns 0 on success and non-zero on failure.
c
int fseek(FILE *stream, long offset, int whence);
Example
This example opens a file, moves the pointer 10 bytes from the start, reads a character, and prints it.
c
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); if (!file) { perror("Failed to open file"); return 1; } // Move pointer 10 bytes from the start if (fseek(file, 10, SEEK_SET) != 0) { perror("fseek failed"); fclose(file); return 1; } int ch = fgetc(file); if (ch == EOF) { printf("No character at this position or read error.\n"); } else { printf("Character at byte 10: %c\n", ch); } fclose(file); return 0; }
Output
Character at byte 10: X
Common Pitfalls
- Not checking if
fseekreturns 0 can cause unnoticed errors. - Using an invalid
whencevalue leads to undefined behavior. - Seeking beyond the file size may cause read/write errors.
- Remember to open the file in a mode that supports the intended operation (read/write).
c
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); if (!file) return 1; // Wrong: using invalid whence // fseek(file, 5, 100); // Invalid whence, do not do this // Right: if (fseek(file, 5, SEEK_CUR) != 0) { perror("fseek failed"); } fclose(file); return 0; }
Quick Reference
| Parameter | Description | Common Values |
|---|---|---|
| stream | File pointer from fopen | FILE * |
| offset | Bytes to move pointer | Positive or negative long |
| whence | Reference point for offset | SEEK_SET, SEEK_CUR, SEEK_END |
Key Takeaways
Use fseek to move the file pointer to a specific byte position in a file.
Always check if fseek returns 0 to confirm success.
Use SEEK_SET, SEEK_CUR, or SEEK_END to specify the starting point for the offset.
Opening the file in the correct mode is essential for fseek to work properly.
Avoid invalid whence values and seeking beyond file boundaries.