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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
int main(int argc, char* argv[]) {
FILE* fp = fopen("o.txt", "w");
size_t position_in_file = ftell(fp); // file position indicator (starts at 0)
printf("ftell(fp) == %zd # just opened file\n", position_in_file);
int n = 0x0a216f59; // changing first two bytes of the int to 0x0a ('\n') so that end of string will be '\n'.
int* a_n = &n;
fwrite(a_n, sizeof(*a_n), 1, fp);
printf("ftell(fp) == %zd # wrote one int\n", ftell(fp));
fclose(fp); // RULE: If you open a file, you must close it (once).
fp = fopen("o.txt", "r");
for(char ch = fgetc(fp); ! feof(fp); ch = fgetc(fp)) {
fputc(ch, stdout); // print just one character
}
// File position indicator goes forward once for every call to fputc(…) or fgetc(…).
fseek(fp, 0, SEEK_SET);
for(char ch = fgetc(fp); ! feof(fp); ch = fgetc(fp)) {
fputc(ch, stdout); // print just one character
}
fclose(fp);
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.