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

int main(int argc, char* argv[]) {
    FILE* fp = fopen("p.txt", "w");  // "w" to write (and replace file if existing)

    // Write a byte using fputc(…)
    fputc(0x41, fp);
    // 0x41 == '\x41' == 'A' == 65 == 01000001₂

    // Write a byte using fwrite(…)
    uint8_t bytes_to_write[] = { 0x42 };

    size_t num_bytes_to_write = sizeof(bytes_to_write) / sizeof(bytes_to_write[0]);
    fwrite(bytes_to_write, sizeof(bytes_to_write[0]), num_bytes_to_write, fp);
    // 0x42 == '\x42' == 'B' == 65 == 01000010₂
    
    // fwrite(bytes_to_write, 1, 1, fp);              // BOO!!!!!
    // fwrite(bytes_to_write, sizeof(uint8_t), 1 fp); // BOO!!!!!
    // fwrite(bytes_to_write, sizeof(0x42), 1 fp);    // WRONG!!!!!

    //___________________________________________________________
    // LESSON:  Use fputc(…) to write a single byte to a file.
    //‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾

    fclose(fp);
    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.