Cover Image for C fseek()
104 views

C fseek()

The fseek() function in C is used to set the file position indicator (cursor) within a file. It allows you to move the cursor to a specific position in the file, which is useful for reading or writing data at a particular location within the file. fseek() is typically used with files opened in binary mode ("rb" for reading or "wb" for writing).

Here’s the prototype of the fseek() function:

C
int fseek(FILE *stream, long int offset, int whence);
  • stream: A pointer to the FILE structure representing the open file.
  • offset: The number of bytes by which the file position indicator is to be moved. A positive value moves the indicator forward, and a negative value moves it backward.
  • whence: An integer that specifies the reference point for the offset. It can take one of the following values:
  • SEEK_SET (0): Set the position relative to the beginning of the file.
  • SEEK_CUR (1): Set the position relative to the current position of the file pointer.
  • SEEK_END (2): Set the position relative to the end of the file.

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

Here are some common uses of fseek():

  1. Move to the Beginning of a File:
C
 fseek(file, 0, SEEK_SET);
  1. Move to the End of a File:
C
 fseek(file, 0, SEEK_END);
  1. Move Forward or Backward a Specific Number of Bytes:
C
 fseek(file, 100, SEEK_CUR); // Move 100 bytes forward from the current position
 fseek(file, -50, SEEK_CUR); // Move 50 bytes backward from the current position
  1. Move to a Specific Position in the File:
C
 fseek(file, 200, SEEK_SET); 
 // Move to the 200th byte from the beginning of the file

Here’s a simple example that demonstrates the use of fseek() to move the cursor within a file:

C
#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "rb"); // Open a file for reading in binary mode

    if (file == NULL) {
        perror("Error opening the file");
        return 1;
    }

    fseek(file, 10, SEEK_SET); // Move to the 10th byte from the beginning of the file

    // Read and print the content from this position
    char buffer[100];
    if (fread(buffer, 1, sizeof(buffer), file) > 0) {
        printf("Data read from the file: %s\n", buffer);
    } else {
        perror("Error reading the file");
    }

    fclose(file); // Close the file

    return 0;
}

In this example, fseek() is used to move to the 10th byte from the beginning of the file, and then data is read and printed from that position.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS