WeCodeAcademy

C File Handling

fopen opens a file, fprintf/fgets write and read it, and fclose closes it. Always check that fopen worked.

ExampleC
#include <stdio.h>

int main(void) {
  const char *path = "/tmp/wecode_demo.txt";

  FILE *out = fopen(path, "w");
  if (out == NULL) { printf("cannot open\n"); return 1; }
  fprintf(out, "line one\n");
  fprintf(out, "line two: %d\n", 42);
  fclose(out);

  FILE *in = fopen(path, "r");
  if (in == NULL) { printf("cannot read\n"); return 1; }
  char line[100];
  int n = 0;
  while (fgets(line, sizeof(line), in) != NULL) {
    n++;
    printf("%d: %s", n, line);
  }
  fclose(in);
  remove(path);
  return 0;
}
Output
1: line one
2: line two: 42
Quick check

What does fopen return if it fails?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.