Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

How to use fseek function in C

Faraz Karim

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 ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring