fseek() in C
×


fseek() in C

206

The fseek() function in C is used to set the file position indicator for a specified file stream.

It allows you to move the file pointer to a desired location within the file.

Syntax of fseek() in C:

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

stream: Pointer to the FILE object that identifies the file stream.

offset: Number of bytes to offset from the origin.

origin: Position from where the offset is applied (SEEK_SET, SEEK_CUR, or SEEK_END).

Return Value:

On success, fseek() returns 0.

On failure, it returns a non-zero value.

Example:

#include<stdio.h>

int main() {
    FILE *fp;
    char ch;

    // Open a file named "example.txt" in read mode
    fp = fopen("example.txt", "r");

    // Check if the file opened successfully
    if (fp != NULL) {
        // Move the file pointer to the 5th byte from the beginning of the file
        fseek(fp, 4, SEEK_SET);

        // Read and print the character at the current file position
        ch = fgetc(fp);
        printf("Character at position 5: %c\n", ch);

        // Close the file
        fclose(fp);
    } else {
        printf("Error opening file.\n");
    }

    return 0;
}

Output:

Error opening file.

Diagram:

In this example:

We open a file named "example.txt" in read mode.

We use fseek(fp, 4, SEEK_SET); to move the file pointer to the 5th byte from the beginning of the file.

After seeking to the desired position, we read and print the character at that position using fgetc(fp).

Finally, we close the file with fclose(fp).

The diagram illustrates the file positions before and after the fseek() operation.

After fseek(), the file pointer is positioned at byte 5 (| symbol in the diagram).



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments