Tsallaka zuwa abun ciki
Justice Tech School

Writing and Reading Files

fopen opens a file, fprintf and fgets write and read, fclose closes. Always check the result.

Example
#include <stdio.h>

int main(void) {
  FILE *f = fopen("/tmp/demo_c.txt", "w");
  if (!f) return 1;
  fprintf(f, "line1\nline2\n");
  fclose(f);
  f = fopen("/tmp/demo_c.txt", "r");
  char buf[40];
  while (fgets(buf, sizeof buf, f)) printf("> %s", buf);
  fclose(f);
  remove("/tmp/demo_c.txt");
  return 0;
}

Result

> line1
> line2

Exercise

Close a file.

(f);

Quiz Test

What does fopen return on failure?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.