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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
int main(int argc, char* argv[]) {
// Create a text file containing "Yo!" plus a null terminator (weird thing to do). This
// time, we create the file using an int to get the right bytes in there. This is just for
// demonstration to make the point in the lecture, that it's all just bytes.
FILE* fp = fopen("m.txt", "w");
int n = 0x00216f59; // 2191193 ← 0x00216f59 is expressed in big endian byte order
int* a_n = &n;
fwrite(a_n, sizeof(*a_n), 1, fp); // fwrite(…) copies bytes from memory to file.
fclose(fp); // RULE: If you open a file, you must close it (once).
// Read an int from the file. This only works because the file contains 4 bytes.
fp = fopen("m.txt", "r"); // mode "r" means we want to read a file. "a" means append to the end
int num_from_file; // will be initialized by fread(…).
int* a_num_from_file = &num_from_file;
fread(&num_from_file, sizeof(*a_num_from_file), 1, fp);
fclose(fp); // RULE: If you open a file, you must close it (once).
printf("num_from_file == 0x%08x # %d\n", num_from_file, num_from_file);
// Open file again (for the third time) so we can read the characters as characters.
fp = fopen("m.txt", "r");
printf("Here are the character values:\n");
printf("______________________________\n");
for(char ch = fgetc(fp); ! feof(fp); ch = fgetc(fp)) {
printf("character value: %02x # %3d # '%c'\n", ch, ch, ch);
}
printf("------------------------------\n");
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2020 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.