fseek() in C

The fseek() function in C is used to move the file pointer to a specific position in a file. This allows for reading or writing data at a particular location within the file. It is a part of the standard input/output library.

Syntax

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

Parameters

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

Example: Using fseek()

                            
#include <stdio.h>
int main() 
{
    FILE *file = fopen("example.txt", "w+");
    if (file == NULL) {
        printf("Error opening file\n");
        return 1;
    }

    // Write data to the file
    fputs("Hello, world!", file);

    // Move the file pointer to the beginning
    fseek(file, 0, SEEK_SET);

    // Read and print the data
    char buffer[50];
    if (fgets(buffer, sizeof(buffer), file) != NULL) {
        printf("Data: %s\n", buffer);
    }             
            
    fclose(file);
    return 0;
}
                            
                        

Output:

Data: Hello, world!

Key Points