C Create Files

Up to now, every program we wrote lost its data the moment it finished running. In this lesson you will learn how to create real files on your computer so your data can live on after the program ends.

In C, working with files is done through a special type called FILE, which lives in the standard input/output library. Before you can create or use any file, you must include <stdio.h> at the top of your program. This header gives you the FILE type and all the functions you need, such as fopen and fclose.

Creating a File with fopen()

The fopen() function is your main tool for working with files. It takes two pieces of information: the name of the file you want to work with, and a mode that tells C what you plan to do. When you open a file in write mode ("w") and that file does not exist yet, C will create it for you automatically.

  • "w" - Write mode. Creates a new file. If the file already exists, its contents are erased.
  • "a" - Append mode. Creates the file if it does not exist, and adds new data to the end if it does.
  • "r" - Read mode. Opens an existing file for reading only. It will not create a new file.

Create a file called notes.txt

#include <stdio.h>

int main() {
    // Open a file in write mode; this creates notes.txt
    FILE *fptr = fopen("notes.txt", "w");

    // Always close the file when you are done
    fclose(fptr);

    printf("File created successfully!\n");
    return 0;
}

Notice that fopen() returns a pointer to a FILE, which we store in a variable called fptr. Think of this pointer as a handle or a bookmark that C uses to keep track of the open file. You will pass this handle to every other file function you call.

Always Check if the File Opened

Sometimes fopen() fails, for example if the folder is read-only or the disk is full. When that happens, it returns a special value called NULL instead of a valid handle. A careful programmer always checks for NULL before using the file, so the program does not crash.

Safely creating a file

#include <stdio.h>

int main() {
    FILE *fptr = fopen("data.txt", "w");

    // Stop if the file could not be created
    if (fptr == NULL) {
        printf("Error: could not create the file.\n");
        return 1;
    }

    printf("data.txt is ready to use.\n");
    fclose(fptr);
    return 0;
}
Note: Every file you open with fopen() should be closed with fclose(). Forgetting to close a file can cause your data to be lost or the file to stay locked. Make closing the file a habit right after you open it.
ModeMeaningCreates file if missing?
"w"Write (erases existing content)Yes
"a"Append (adds to the end)Yes
"r"Read onlyNo