C Programming

Fseek in C

This quick guide discusses how to use the C fseek library function. The fseek function sets a file position indicator for a set file stream to a given offset value.

Basic Usage

The general syntax for this function is:

int fseek (FILE *stream, int offset, int origin);

Fseek Parameters

The function supports three parameters:

  1. stream – Pointer to the file object.
  2. offset – Number of offset bytes from the start position.
  3. origin – Position where the offset values are added.

The fseek origin values include:

  1. SEEK_SET – Beginning of the file.
  2. SEEK_CUR – The current cursor position.
  3. SEEK_END – End of file.

The fseek function returns zero on success and a non-zero value on failure.

Example 1

Suppose we have a text file with the contents as:

“Hello world!,

This is C language calling for you!

Are you going you going to answer?

We can use SEEK_END to move the pointer to the end of the file. Consider the example code shown below:

#include <stdio.h>

int main() {

    FILE *file;

    file = fopen("readme.txt", "r");

    fseek(file, 0, SEEK_END);

    printf("%ld\n", ftell(file));

    return 0;

}

The cursor moves to the end and prints the pointer position. Since we set the offset value after the end of the file to 0, it prints 91 as it pointer position.

gcc fseek.c

./a.out

91

Example 2

To move to a specific position using fseek, we can simply use the SEEK_SET to move the specified number of bytes from the beginning of the file.

An example code is as shown:

#include <stdio.h>

int main() {

    FILE *file;

    file = fopen("readme.txt", "r");

    fseek(file, 10, SEEK_SET);

    printf("%ld\n", ftell(file));

    return 0;

}

In the above example, we tell the pointer to move 10 bytes. This should return 10 as the current pointer position.

./a.out

10

Conclusion

This short tutorial has shown you how to use the fseek function in C. Check the manual to learn more.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list