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

// This method is NOT recommended for HW16.

int main(int argc, char* argv[]) {
    char const* filename = "b.txt";

    log_yellow("___________________________\n");
    log_yellow("OPEN file for writing (mode \"w\")\n");
    FILE* fp = fopen(filename, "w");

    log_yellow("WRITE to file\n");
    // fputs('A', fp);
    // fputc('B', fp);
    // fputc('C', fp);
    fputs("ABC", fp);  // equivalent to the above

    log_yellow("CLOSE file\n");
    fclose(fp);

    log_yellow("___________________________\n");
    log_yellow("OPEN file for reading (mode \"r\")\n");
    // Read the file using fread(…) -- NOT RECOMMENDED FOR HW16
    size_t num_chars_in_file = 3;
    char* s = malloc((num_chars_in_file + 1) * sizeof(*s));

    fp = fopen(filename, "r");
    fread(s, sizeof(*s), num_chars_in_file, fp);
    fclose(fp);

    s[num_chars_in_file] = '\0';

    log_str(s);

    free(s);

    
    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.