Search notes:

libc: lseek and fseek

lseek

#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>      // printf()
#include <stdlib.h>     // exit()


int main() {

    int fd = open("words.txt", O_RDONLY);
    if (fd < 0) exit(1);

    char word[4];

    off_t new_pos = lseek(fd, 4, SEEK_SET);
    read(fd, word, 3);
    word[4] = 0;

    printf("Word @ pos %d: %s\n", new_pos, word);

    new_pos = lseek(fd, 1, SEEK_CUR); // Skip new line characters

    read(fd, word, 3);
    printf("Word @ pos %d: %s\n", new_pos, word);

    close(fd);

}
Github repository about-libc, path: /functions/seek/lseek.c
If successful, lseek returns the new offset from the beginning of the file in bytes.
If not successful, lseek returns -1.

fseek

#include <stdio.h>

#include <stdlib.h>     // exit()

int main() {

    FILE *f = fopen("words.txt", "r");
    if (!f) exit(1);

    char word[4];
    word[4] = 0;   // Words contain three characters.

    if (fseek(f, 4, SEEK_SET)) exit(2);

 //
 // We want to read 3 chars:
 //
    size_t size  = sizeof(char);
    size_t nmemb =           3 ;

    size_t nof_items_read = fread(word, size, nmemb, f);
    if (nof_items_read != 3) exit(3);

    printf("Word: %s\n", word);

 //
 // Advance file position indicator by one character:
 //
    if (fseek(f, 1, SEEK_CUR)) exit(4);

 //
 // Read another word
 //
    nof_items_read = fread(word, size, nmemb, f);
    if (nof_items_read != 3) exit(3);

    printf("Word: %s\n", word);

    fclose(f);

}
Github repository about-libc, path: /functions/seek/fseek.c
If successful, fseek returns 0.

words.txt

words.txt is the file that is being seeked on. It consists of three words, each being three characters long. Each word is terminated by a new line. Thus, the total size of words.txt is 12 bytes.
foo
bar
baz
Github repository about-libc, path: /functions/seek/words.txt

See also

The Perl function seek
The Standard C Library

Index