C Programming Tutorial

C Programming Tutorial

fseek() in C Programming

Hello Everyone, In this article, we will discuss about fseek() in C Programming. This function is essential for file handling, as it allows you to move the file pointer to a specific location within a file. Understanding fseek() can help you read from and write to files more efficiently. Whether you are new to C or have some experience, this guide will help you to understand basics of fseek() in C effectively with examples. Let’s get started.

Definition of fseek Function

fseek() is a standard library function in C programming that allows you to set the position indicator of a file stream. This means you can move the “cursor” to any position in the file and start reading or writing from there.

Syntax for fseek()

int fseek(FILE *stream, long int offset, int whence);

The parameters of the function are:

  • stream: A pointer to a FILE object that specifies the file to set the position in.
  • offset: A long integer value that specifies the number of bytes to offset the position indicator. This value can be positive or negative.
  • whence: An integer value that specifies the reference point used to calculate the new position. It can take one of the following values:
    • SEEK_SET (0): The new position is offset bytes from the beginning of the file.
    • SEEK_CUR (1): The new position is offset bytes from the current position indicator.
    • SEEK_END (2): The new position is offset bytes from the end of the file.

Return Value: The fseek() function returns zero on success, and a non-zero value on failure.

Here’s an example code that shows how to use fseek() to move the position indicator in a file:

#include <stdio.h>

int main() {
   FILE *fp = fopen("example.txt", "r");
   if(fp == NULL) {
      perror("Error opening file");
      return -1;
   }

   // Move the position indicator to the 10th byte from the beginning of the file
   if(fseek(fp, 10, SEEK_SET) != 0) {
      perror("Error setting position");
      return -1;
   }

   // Read the next 5 characters from the file
   char buf[6];
   if(fread(buf, 1, 5, fp) != 5) {
      perror("Error reading file");
      return -1;
   }

   // Print the characters we just read
   buf[5] = '\\0'; // Make sure we terminate the string
   printf("%s\\n", buf);

   fclose(fp);
   return 0;
}

In this example, we first open the file “example.txt” for reading using fopen(). We then use fseek() to move the position indicator to the 10th byte from the beginning of the file. Finally, we use fread() to read the next 5 characters from the file starting at the position indicator we just set. We print these characters to the console using printf(), and then close the file using fclose().

Share This Article