Files

Write and read text and binary files with fopen, fprintf and fscanf.

C
#include <stdio.h>

int main(void) {
  FILE *f = fopen("marks.txt", "w");
  if (f == NULL) {
    perror("marks.txt");
    return 1;
  }
  fprintf(f, "Kavin 72\nDivya 95\nRavi 60\n");
  fclose(f);

  f = fopen("marks.txt", "r");
  if (f == NULL) {
    perror("marks.txt");
    return 1;
  }
  char name[32];
  int marks, total = 0, count = 0;
  while (fscanf(f, "%31s %d", name, &marks) == 2) {
    printf("%s: %d\n", name, marks);
    total += marks;
    count++;
  }
  fclose(f);
  printf("Average %.1f\n", (double) total / count);
  return 0;
}
Output
Kavin: 72
Divya: 95
Ravi: 60
Average 75.7

Always check fopen for NULL: the file may be missing, or you may not have permission. perror prints the reason. fscanf returns how many values it read, so the loop stops cleanly at the end of the file. %31s stops a long name overflowing the 32-byte buffer.

ModeMeaning
"r"Read; the file must exist
"w"Write; creates the file, or empties it if it exists
"a"Append to the end
"r+"Read and write an existing file
"rb" / "wb"Binary files, such as images or saved structs

Binary files

C
#include <stdio.h>

struct Student {
  int id;
  double cgpa;
};

int main(void) {
  struct Student out[2] = {{101, 8.4}, {102, 9.1}};
  FILE *f = fopen("students.dat", "wb");
  if (f == NULL) {
    return 1;
  }
  fwrite(out, sizeof out[0], 2, f);
  fclose(f);

  struct Student in[2];
  f = fopen("students.dat", "rb");
  if (f == NULL) {
    return 1;
  }
  size_t n = fread(in, sizeof in[0], 2, f);
  fclose(f);
  printf("%zu %d %.1f\n", n, in[1].id, in[1].cgpa);
  return 0;
}
Output
2 102 9.1

fwrite copies the bytes of the structs straight to disk, which is fast. The file can only be read back by a program with the same struct layout, so use text or JSON for files that other programs need.

โ† Memory and structsBitwise operators โ†’