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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

// FILES - how to read a file one character at a time
//
// CAUTION: Googling this may make your life harder.
//
// char has range -128 to 127 and is usually used for human-readable text.
// unsigned char has range 0 to 255  and can include binary bytes and unprintable stuff

int main(int argc, char* argv[]) {
    // OPEN FILES
    FILE* fp = fopen("3.read_file.txt", "r");   // takes filename and mode
    // mode can be "r" - to read the file
    //             "w" - to write the file from the beginning (truncates if file exists)
    //             "a" - to write the file from the end (leaving existing contents if any)

    // READ CHARACTERS ONE BY ONE
    for(char ch = fgetc(fp); !feof(fp); ch = fgetc(fp)) {
        fputc(ch, stdout);
    }
    // fgetc(…) is a function that gets one character from the file and advances the
    //     file position by one character.  The next time is called, it will get the
    //     next character in the file.  We read the file start to finish.  Going
    //     backwards is not covered, yet.  After it has read the last character, it
    //     returns a special value, called EOF.  EOF is defined in stdio.h as -1.
    //
    // feof(fp) returns true (1) if fgetc(…) has returned EOF.
    //
    // STRONG RECOMMENDATION: Do not use EOF.  It leads to bugs.

    // Always close file when you are done with it.
    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.