Example 1 — Write then read a short file
The complete open-use-close cycle.
#include <stdio.h>
int main(void) {
FILE *out = fopen("notes.txt", "w");
if (!out) { perror("notes.txt"); return 1; }
fputs("learning C file I/O\n", out);
fclose(out);
char buf[64];
FILE *in = fopen("notes.txt", "r");
if (!in) { perror("notes.txt"); return 1; }
if (fgets(buf, sizeof buf, in)) printf("read: %s", buf);
fclose(in);
return 0;
} How It Works
fputswrites the string and the newline already in it.- Each
fopenis paired with anfclose. perrorprints a readable message if a file cannot be opened.
