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>
// fputc vs. fwrite
//
// fputc(…) writes one byte at a time.
// fwrite(…) writes any number of bytes.
typedef unsigned char uchar;
int main(int argc, char* argv[]) {
FILE* fp = fopen("b.txt", "w"); // "w" means write (and replace file if it exists).
// Write one byte ('A' == 0x41 == 65 == 01000001₂) using fputc(…).
fputc(0x41, fp);
// Write one byte ('B' == 0x42 == 66 == 01000010₂) using fwrite(…).
uchar src_data[] = { 0x42 };
fwrite(src_data, sizeof(src_data[0]), 1, fp); // too much risk of getting it wrong
// fwrite(src_data, 1, 1, fp); // BOO!!!!!!!
// fwrite(src_data, sizeof(uchar), 1, fp); // BOO!!!!!!!
// fwrite(src_data, sizeof(0x42), 1, fp); // WRONG!!!!!
// LESSON: Use fputc(…)
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.