Example 1 — The standard streams are FILE pointers
Use the same function for the screen or a file.
#include <stdio.h>
static void report(FILE *out, const char *msg) {
fprintf(out, "%s\n", msg);
}
int main(void) {
report(stdout, "writing through a FILE *");
printf("stdout is a FILE *: %d\n", stdout != NULL);
FILE *fp = fopen("log.txt", "w");
if (fp) {
report(fp, "saved to a file");
fclose(fp);
printf("log.txt written\n");
}
return 0;
} How It Works
reportaccepts anyFILE *, whether screen or disk.- The first call writes to
stdout. - The second writes the same text into
log.txt.
