Nearby lessons

67 of 72

C - Create a File

In C, you can create a file by opening it with a suitable write mode using fopen(). This lesson shows how to create a text file and check whether the operation succeeds.

1. Create a File Using fopen()

Open the file using "w". If the file does not exist, C creates it. If it already exists, its previous contents are erased.

Example01
CCode Cell
1#include <stdio.h>
2 
3int main(void) {
4 FILE *fp = fopen("data.txt", "w");
5 
6 if (fp == NULL) {
7 printf("Could not create the file\n");
8 return 1;
9 }
10 
11 fprintf(fp, "This file was created using C.\n");
12 fclose(fp);
13 
14 printf("data.txt created successfully\n");
15 return 0;
16}
Output
data.txt created successfully

2. Important Note About the w Mode

If data.txt already contains information, opening it with "w" removes the old contents immediately. Be careful when using this mode with important files.

3. Where Is the File Created?

If you provide only a filename such as "data.txt", the file is normally created in the program's current working directory. If you provide a folder path, that folder must already exist; fopen() does not create folders.

📝 Key Takeaways
  • There is no separate standard C function named create-file for basic file creation.
  • Opening with w or a creates a file if it is missing.
  • Opening an existing file with w erases its contents.
  • The file is normally created in the program current working directory when only a filename is given.

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3