C - Simple File Handling

Use fopen, fclose, fprintf, fscanf, and fgets for basic file operations.

Learning Objectives

  • Open, read, write, and close text files safely.

Example: write then read

#include <stdio.h>

int main(void) {
  FILE *fp = fopen("out.txt", "w");
  if (!fp) return 1;
  fprintf(fp, "Hello file!\n");
  fclose(fp);
  
  fp = fopen("out.txt", "r");
  if (!fp) return 1;
  char line[64];
  if (fgets(line, sizeof line, fp)) {
    printf("%s", line);
  }
  fclose(fp);
}

Common Pitfalls

  • Forgetting to check fopen return value for NULL.
  • Not closing files with fclose.