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
50
51
52
53
54
55
56
57
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <string.h>

// okay to copy/adapt
char* _read_file_into_string(char const* filename) {
    FILE* file = fopen(filename, "r");

    // for loop, calling getc() until I reach the end of the file
    // fseek(file, n, SEEK_CUR); // increase my position by n
    // fseek(file, n, SEEK_SET); // set position to n
    // fseek(file, -n, SEEK_END); // set position to end of file
    //                               offset backwardw by -n
    // e.g. -10 would be 10 characters before the end

    // seek to the end of the file
    fseek(file, 0, SEEK_END); // SEEK_END is relative to the end
    int file_len = ftell(file); // does not include space for
                                // null terminator
    printf("Size is %d\n", file_len + 1);

    // seek to character at index 0 in the file
    fseek(file, 0, SEEK_SET); // SEEK_SET is relative to the start

    char* str = malloc(sizeof(*str) * (file_len + 1));
    int i = 0;
    for (char ch = fgetc(file); !feof(file); ch = fgetc(file)) {
        str[i] = ch;
        i++;
    }
    assert(i == file_len);

    // DON'T FORGET THE NULL TERMINATOR!!
    str[file_len] = '\0';

    // DON'T FORGET TO CLOSE THE FILE!!
    fclose(file);

    printf("Value is '''\n%s\n'''\n", str);

    return str;
}


int main(int argc, char* argv[]) {
    char* file_contents = _read_file_into_string("example.txt");    

    assert(file_contents != NULL);
    assert(strcmp(file_contents, "Hello World\n") == 0);

    free(file_contents);

    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.