🎓 A1Learner
🔍
0 of 50 lessons completed

C Create Files

Printed words vanish when the program ends. A program creates a text file on disk with fopen, and the write mode makes a new empty file.

Create a file

notes.txt did not exist, and write mode made it. The output confirms the file was created.

#include <stdio.h>

int main() {
  FILE *fp = fopen("notes.txt", "w");
  if (fp == NULL) {
    printf("Could not create notes.txt.\n");
    return 1;
  }
  fclose(fp);
  printf("notes.txt created.\n");
  return 0;
}

Create a second file

The same steps make scores.txt instead. The output names the new file.

#include <stdio.h>

int main() {
  FILE *fp = fopen("scores.txt", "w");
  if (fp == NULL) {
    printf("Could not create scores.txt.\n");
    return 1;
  }
  fclose(fp);
  printf("scores.txt created.\n");
  return 0;
}

Create a diary file

A third name, diary.txt, works the same way. The output names the file it created.

#include <stdio.h>

int main() {
  FILE *fp = fopen("diary.txt", "w");
  if (fp == NULL) {
    printf("Could not create diary.txt.\n");
    return 1;
  }
  fclose(fp);
  printf("diary.txt created.\n");
  return 0;
}

Example

#include <stdio.h>

int main() {
  FILE *fp = fopen("report.txt", "w");
  if (fp == NULL) {
    printf("Could not create report.txt.\n");
    return 1;
  }
  fclose(fp);
  printf("report.txt created.\n");
  return 0;
}

Key points

  • fopen opens a file and gives back a pointer to it.
  • FILE is the type for a file pointer.
  • fopen("notes.txt", "w") opens notes.txt in write mode.
  • Write mode creates the file when it does not exist yet.
  • Write mode empties a file that already exists.
  • fopen gives back NULL when the file cannot be opened.
  • Check the result against NULL before using the pointer.
  • fclose closes the file when the program is done with it.

fopen opens report.txt in write mode, the NULL check passes, and the file is closed. The output names the file that was created.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which call opens notes.txt in write mode?