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
#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");
    
    // 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
    // seek to character at index 0 in the file
    rewind(file);

    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);

    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);

    printf("String is %s", file_contents);

    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.