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
45
46
47
48
49
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "clog.h"

// 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");  // mode "r" means read file
                                      // mode "w" means write file (overwrite if exists)
                                      // mode "a" means append to end of file

    logf_yellow("Read file one character at a time.\n");
    
    for(char ch = fgetc(fp); ! feof(fp); ch = fgetc(fp)) {
        fputc(ch, stdout);
    }
    /*
     File pointer keeps track of the "file position indictor" (position in file).
     ∙ fgetc(…) reads the next character and then advances the file position indictor.
        - Same for fputc(…), fprintf(…), fputs(…), and others.
     ∙ fgetc(…) returns the next character or, if we have reached the end of the file,
       it returns EOF, a constant the means "end of file".
        - Value of EOF is -1, but most of the time there's no need to remember that.
        - We do NOT recommend using EOF to control your loop.  It is bug-prone.
     ∙ feof(…) returns true (or equivalent) if fgetc(…) has reached the end of the file
       and returned EOF.

     EOF does not exist in the file.
     '\0' is for memory.  It does not terminate files.
     */

    logf_yellow("\nClose the file.\n");
    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.