C Write Files

Creating an empty file is only half the job. In this lesson you will learn how to actually put text and numbers inside a file using the fprintf() function, so your program can save useful information.

To write into a file, you first open it in write mode ("w") or append mode ("a"), and then use a function to send text into it. The most common function for this is fprintf(), which works almost exactly like the printf() you already know, except it sends the text into a file instead of the screen.

Writing with fprintf()

The only difference between printf() and fprintf() is that fprintf() takes one extra piece of information at the front: the file handle you got from fopen(). Everything after that is the same format string and values you are used to.

Write a line of text to a file

#include <stdio.h>

int main() {
    FILE *fptr = fopen("greeting.txt", "w");
    if (fptr == NULL) {
        printf("Could not open the file.\n");
        return 1;
    }

    // Send text into the file instead of the screen
    fprintf(fptr, "Hello from C!\n");
    fprintf(fptr, "Writing files is easy.\n");

    fclose(fptr);
    printf("Text saved to greeting.txt\n");
    return 0;
}

Because fprintf() supports format specifiers, you can mix variables and text together just like with printf(). This makes it perfect for saving numbers, names, and calculated results into a file.

Write variables into a file

#include <stdio.h>

int main() {
    char name[] = "Ada";
    int score = 95;

    FILE *fptr = fopen("result.txt", "w");
    if (fptr == NULL) {
        return 1;
    }

    // %s inserts the name, %d inserts the number
    fprintf(fptr, "Player: %s\n", name);
    fprintf(fptr, "Score: %d\n", score);

    fclose(fptr);
    return 0;
}

Write Mode vs Append Mode

  • Opening with "w" erases whatever was already in the file before writing your new text.
  • Opening with "a" keeps the old content and adds your new text to the very end.
  • Use "a" when you want to build up a log or add records over many runs of your program.
Note: Be careful with "w" mode. If you open an important file in write mode, its old contents disappear immediately, even if you never write anything new. When in doubt, use append mode ("a") to protect existing data.
FunctionBest used forExample
fprintf()Formatted text and numbersfprintf(fptr, "Age: %d\n", age);
fputs()Writing a plain stringfputs("Hello\n", fptr);
fputc()Writing a single characterfputc('A', fptr);