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 | #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).
FILE* fp = fopen("i.txt", "w");
fprintf(fp, "Yo!");
fputc('\0', fp); // This is WEIRD. Normally: Do not write '\0' to a text file.
fclose(fp); // RULE: If you open a file, you must close it (once).
// Read the file, one character at a time.
printf("Here are the characters:\n");
printf("________________________\n");
fp = fopen("i.txt", "r"); // mode "r" means we want to read a file. "a" means append to the end
for(char ch = fgetc(fp); ! feof(fp); ch = fgetc(fp)) {
// fgetc(…) reads a single character from a file. Might return EOF (special value).
// feof(…) returns true if you have encountered the EOF (end of file) marker,
// i.e., if you have read past the end of the file.
fputc(ch, stdout); // Write one character to stdout.
}
fclose(fp); // RULE: If you open a file, you must close it (once).
printf("\n------------------------\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.