C programming stdio.h function - int fseek(FILE *stream, long int offset, int whence)

ww‮figi.w‬tidea.com

In C programming, the fseek() function is defined in the stdio.h header file and is used to set the file position indicator for the specified stream. The function takes the following three arguments:

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

The first argument, stream, is a pointer to a FILE object that represents the stream whose position indicator is to be set. The second argument, offset, is a long integer value that specifies the number of bytes to be offset from the origin of the file. The third argument, whence, is an integer value that specifies the origin from which to calculate the offset. The whence argument can be one of the following values:

  • SEEK_SET - the offset is calculated from the beginning of the file
  • SEEK_CUR - the offset is calculated from the current position of the file pointer
  • SEEK_END - the offset is calculated from the end of the file

The fseek() function sets the position indicator for the specified stream to the value obtained by adding offset bytes to the position specified by whence. The function returns zero if the operation is successful, and a nonzero value otherwise.

Here's an example of how to use fseek() to move the file pointer to a specific position within a file:

#include <stdio.h>

int main() {
    FILE *fp;
    char buffer[1024];

    fp = fopen("example.txt", "r");
    if (fp == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    fseek(fp, 10L, SEEK_SET);
    fgets(buffer, 1024, fp);
    printf("The 11th character is: %c\n", buffer[0]);

    fclose(fp);

    return 0;
}

In the above example, the fseek() function is used to move the file pointer for the fp stream to the 11th character in the file. The fseek() function is called with an offset of 10 bytes and a whence argument of SEEK_SET. After the file pointer is moved, the fgets() function is used to read the next line from the file into a buffer, and the first character of the buffer is printed to the console.