fseeko - Linux


Overview

fseeko is a standard library function in C that allows repositioning the file offset of an open file descriptor to a specified location. It provides fine-grained control over file navigation, enabling precise seek operations. This is particularly useful in scenarios where precise positioning within a file is crucial, such as in file I/O operations, data parsing, or database management.

Syntax

off_t fseeko(FILE *stream, off_t offset, int whence);

Parameters

  • stream: A pointer to the file descriptor of the file to be repositioned.
  • offset: The desired file offset to reposition to, specified in bytes.
  • whence: An integer value indicating the reference point for offset calculation:
    • SEEK_SET: Beginning of the file
    • SEEK_CUR: Current file position
    • SEEK_END: End of the file

Options/Flags

There are no specific options or flags associated with fseeko.

Examples

Example 1: Seeking to the beginning of a file

FILE *fp = fopen("myfile.txt", "r");
fseeko(fp, 0, SEEK_SET);

Example 2: Moving 10 bytes forward from the current position

fseeko(fp, 10, SEEK_CUR);

Example 3: Seeking to the end of a file

fseeko(fp, 0, SEEK_END);

Common Issues

  • Negative offset: Attempting to seek to a negative offset will result in an error and leave the file pointer unchanged.
  • Out-of-range offset: Seeking to an offset beyond the end of the file will also result in an error.

Integration

fseeko can be combined with other file I/O functions, such as fread and fwrite, to perform advanced file manipulations. For example:

Example: Copying data from one file to another with precise control

FILE *source = fopen("source.txt", "r");
FILE *target = fopen("target.txt", "w");
fseeko(source, 10, SEEK_SET); // Skip the first 10 bytes in the source file
fseeko(target, 0, SEEK_SET); // Start writing at the beginning of the target file
while (!feof(source)) {
    char buffer[1024];
    size_t bytes_read = fread(buffer, 1, sizeof(buffer), source);
    fwrite(buffer, 1, bytes_read, target);
}

Related Commands

  • ftell: Returns the current file offset of a file pointer.
  • rewind: Resets the file pointer to the beginning of the file.