1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "clog.h"

// ftell(…) returns the position in the file where we will read or write next.

// OK to copy/adapt this function if you understand it completely.
char const* write_file(char const* contents, char const* filename) {
    FILE* fp = fopen(filename, "w");
    fputs(contents, fp);
    fclose(fp);
    return filename;
}

int main(int argc, char* argv[]) {
    logf_yellow("Write \"ABC\" to file.\n");
    char const* filename = write_file("ABC", __FILE__ ".txt");
    
    logf_yellow("Open the file.\n");
    FILE* fp = fopen(filename, "r");
    int position_after_opening_file = ftell(fp);
    log_int(position_after_opening_file);

    /*
        'A'  'B'  'C'
         0    1    2      ftell(…) returns this just before calling fgetc(…)
     */
    logf_yellow("Read file one character at a time.\n");
    for(char ch = fgetc(fp); ! feof(fp); ch = fgetc(fp)) {
        int position = ftell(fp);
        printf("Character '%c' found at position %d.\n", ch, (position - 1));
        // -1 because we called ftell(…) after we read the character.
    }

    logf_yellow("\nClose the file.\n");
    int position_just_before_closing_file = ftell(fp);
    log_int(position_just_before_closing_file);
    fclose(fp);

    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2022 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.