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
58
59
60
61
62
63
// UNTESTED -- This is intended to test if a file contains the expected contents.

// Okay to copy/adapt if you undersand it.  You are responsible for making sure it is correct.

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>

bool _does_file_contain_expected_contents(char* path, uint8_t const* expected_contents, size_t expected_length) {
    bool file_contents_match = true;

    FILE* fp = fopen(path, "r");
    if(fp == NULL) {
        file_contents_match = false;  // File not found.
    }
    else {
        size_t num_bytes_read = 0;
        for(uint8_t ch = fgetc(fp); !feof(fp) && num_bytes_read < expected_length; ch = fgetc(fp)) {
            num_bytes_read += 1;
            if(ch != expected_contents[num_bytes_read - 1]) {
                file_contents_match = false;  // i'th byte in file is different from i'th byte in expected_contents.
            }
        }

        if(num_bytes_read != expected_length) {
            file_contents_match = false;  // File is longer or shorter than expected_contents.
        }

        fclose(fp);
    }
    return file_contents_match;
}

bool _write_to_file(char const* path, uint8_t* contents, size_t num_bytes) {
    FILE* fp = fopen(path, "w");
    if(fp == NULL) {
        return false; // Unable to write to file.
    }

    for(int i = 0; i < num_bytes; i++) {
        fputc(contents[i], fp);
    }
    fclose(fp);

    return true; // Success
}

int main(int argc, char* argv[]) {
    uint8_t s[] = "happy purple sunflowers";
    size_t s_length = sizeof(s) / sizeof(s[0]); // only works for array on stack (declared with [])
    char const* path = "input.txt";
    _write_to_file(path, s, s_length);

    bool does_match = _does_file_contain_expected_contents(path, s, s_length)

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

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