Sobes.tech
Junior — Middle

Could you explain the purpose and usage of the fseek function when working with files?

sobes.tech AI

Answer from AI

The fseek function in C/C++ is used to move the current position indicator in a file for reading or writing. It allows setting the position in the file relative to the beginning, current position, or end of the file, which is convenient for random access to data.

Syntax:

int fseek(FILE *stream, long offset, int whence);
  • stream — pointer to the file.
  • offset — offset in bytes.
  • whence — reference point, can take values:
    • SEEK_SET — beginning of the file,
    • SEEK_CUR — current position,
    • SEEK_END — end of the file.

Example usage:

FILE *file = fopen("example.txt", "r");
if (file) {
    // Move 10 bytes from the beginning of the file
    fseek(file, 10, SEEK_SET);
    char buffer[100];
    fgets(buffer, sizeof(buffer), file);
    printf("Read line: %s", buffer);
    fclose(file);
}

Thus, fseek allows efficient management of the file position for reading or writing.