cs24-20fa fseek, ftell

Introduction to Computing Systems (Fall 2020)

Name

fseek, ftell - reposition a file stream

Synopsis

#include <stdio.h>

int fseek(FILE *stream, long offset, int seek_type);
long ftell(FILE *stream);

Description

fseek() moves the current position of the file stream stream. The new position, measured in bytes, is obtained by adding offset to the position specified by seek_type. There are three possible values of seek_type:

ftell() gets the current position of the stream in its file (measured in bytes from the start of the file).

Example

// You can use fseek() and ftell() together to get the size of a file

#include <stdio.h>

int main() {
    /* Open a file and seek to its end.
     * Then get the current position in the file, which is its length. */
    FILE *file = fopen("test.txt", "r");
    fseek(file, 0, SEEK_END);
    size_t file_size = ftell(file);
    printf("The file is %zu bytes long\n", file_size);

    // Seek back to the start of the file and read the file_size characters
    fseek(file, 0, SEEK_SET);
    char contents[file_size];
    fread(contents, 1, file_size, file);
    for (size_t i = 0; i < file_size; i++) {
        printf("Char %zu is '%c'\n", i, contents[i]);
    }
    fclose(file);
}

Return Value

Upon successful completion, fseek() returns 0. Otherwise, -1 is returned and errno is set to indicate the error. ftell() returns the current offset.

Errors

EINVAL
The whence argument to fseek() was not SEEK_SET, SEEK_END, or SEEK_CUR. Or: the resulting file offset would be negative.
ESPIPE
The file descriptor underlying stream is not seekable (e.g., it refers to a pipe, FIFO, or socket).

fseek() and ftell() may also fail and set errno for any of the errors specified for fflush(), fstat(), lseek(), and malloc().

See Also

fopen(), fread(), fwrite(), fflush(), fclose()