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

// Okay to copy/adapt this code for ECE 26400 Spring 2022 at your own risk if you understand completely.

typedef unsigned char uchar;

void write_file(const char* filename, const uchar* contents, size_t length_bytes) {
    FILE* fp = fopen(filename, "w");
    for(int i = 0; i < length_bytes; i++) {
        fputc(contents[i], fp);
    }
    fclose(fp);
}

bool do_file_contents_match(const char* filename, const uchar* expected_contents, size_t expected_size) {
    bool does_match = true;

    FILE* fp = fopen(filename, "r");
    for(int i = 0; i < expected_size; i++) {
        uchar ch = fgetc(fp);
        if(feof(fp) || ch != expected_contents[i]) {
            does_match = false;
            break;
        }
    }

    // If contents matched so far, then we should not have reached EOF, yet.
    assert(! (does_match && feof(fp)) );

    // Make sure we are at the end of the file now.
    if(does_match) {
        // Call fgetc(fp).  We don't care what it returns.  If it returned EOF, then feof(fp)
        // will return true after that.
        fgetc(fp);
        if(!feof(fp)) {
            does_match = false;
        }
    }

    fclose(fp);

    return does_match;
}

int main(int argc, char* argv[]) {
    const char* filename = "test_bit_writer_idea.txt";
    const uchar contents[] = { 'A', 'B', 'C', '\xaa', '\xbb', '\xcc' };
    size_t length_bytes = sizeof(contents) / sizeof(contents[0]);
    write_file(filename, contents, length_bytes);
    assert( do_file_contents_match(filename, contents, length_bytes) );

    // Make sure it also reports if the contents are wrong.
    const uchar different[] = { 'A', 'B', 'C', '\xaa', '\xbb', '\xcc', '\xdd' };
    length_bytes = sizeof(different) / sizeof(different[0]);
    assert( length_bytes == 7 );
    assert( ! do_file_contents_match(filename, different, length_bytes) );
    
    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.