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

typedef unsigned char uchar;

// Untested illustration - incomplete
//
// OK to copy/adapt anything in this file.

void write_file(char const* filename, uchar const* contents, size_t num_bytes) {
    FILE* fp = fopen(filename, "w");
    for(size_t i = 0; i < num_bytes; i++) {
        uchar char_to_write = contents[i];
        fputc(char_to_write, fp);  // write one character
    }
    fclose(fp);
}

bool does_file_match(char const* filename, uchar const* expected, size_t num_bytes) {
    // This is an untested illustration.  You may use it as a starting point, but you 
    // will need to fill in some logic for the index in expected that you need to check
    // against.
    //
    // CAUTION:  Be sure to consider the case where the file contains more or fewer
    // than 'num_bytes' bytes.
    //
    // CAUTION:  Call this only after the file has been full written---and closed.
    FILE* fp = fopen(filename, "r");
    bool does_match = true;
    for(uchar ch = fgetc(fp); !feof(fp); ch = ) {
        if(ch != expected[]) {
            does_match = false;
        }
    }
    fclose(fp);
    return does_match;
}

int main(int argc, char* argv[]) {
    uchar const contents[] = { '\xde', '\xca', '\xf0', 'B' };
    size_t num_bytes = sizeof(contents) / sizeof(contents[0]);  // see warning below
    write_file("quiz4.txt", contents, num_bytes);

    mu_check( does_file_match("quiz4.txt", contents, num_bytes) );

    return EXIT_SUCCESS;
}

// WARNING:  You can only use sizeof(…) to get size of an array that was declared
// with […] on stack.
//
// char s1[] = "ABC";
// size_t size_of_s1 = sizeof(s1) / sizeof(s1[0]);  // OK
//
// char* s2 = "ABC";
// // size_t size_of_s1 = sizeof(s1) / sizeof(s1[0]);  // BAD!!!!

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