Trusted answers to developer questions

How to use fseek function in C

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

What it does

fseek is a function in the C library that allows the user to set the file pointer at a specific offset.

Function syntax

Below is the declaration for fseek:

Parameters

fp: The pointer to the FILE object that you intend to access.

offset: The number of bytes to offset from the whence position.

whence: The position at which the file object is accessed and the point from which the offset is added. The whence position can be specified using the following 3 constants:

  • SEEK_SET – Places file pointer at the beginning of the file.

  • SEEK_CUR – Places file pointer at a given position.

  • SEEK_END – Places file pointer at the end of file.

Return Value

The fseek function returns zero if it executes without error. Otherwise, it returns a non-zero value.

Example

In the following example, we open a text file (placed in the same directory) and print everything after the first word, “hello”:

main.c
myFile.txt
#include <stdio.h>
// function that prints from the file pointer til
// the end of file
void print_onwards(FILE* myfile)
{
int i;
while( (i = fgetc(myfile)) != EOF)
putchar(i);
}
int main()
{
FILE *myfile;
myfile = fopen("myFile.txt", "r");
// Placing file pointer after hello
// (5 characters == 5 bytes)
fseek(myfile, 5, SEEK_SET);
print_onwards(myfile);
return 0;
}

In the example above, we placed the file pointer myfile at an offset of 5 bytes from the SEEK_SET position. This means we skipped the first 5 characters of “Hello”. We then printed the file from the position of the file pointer until the end of the file using the print_onwards function.

RELATED TAGS

c

CONTRIBUTOR

Faraz Karim
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?