Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C Files: Create and Write

Variables disappear when a program ends. To keep data, a program writes it to a file. In our editor, files your program creates appear in the file list, where you can open and download them.

Opening and writing a file

fopen(name, mode) opens a file and returns a FILE *, a pointer used by all file functions. Mode "w" creates the file, or empties it if it exists. fprintf writes to a file the way printf writes to the screen. fclose finishes the file.

#include <stdio.h>

int main(void) {
    FILE *f = fopen("marks.txt", "w");
    if (f == NULL) {
        printf("Could not create marks.txt\n");
        return 1;
    }
    fprintf(f, "Asha %d\n", 91);
    fprintf(f, "Ravi %d\n", 78);
    fputs("Meera 85\n", f);
    fclose(f);
    printf("marks.txt written.\n");
    return 0;
}
Output
marks.txt written.

Always check for NULL: fopen fails when a folder does not exist or a file cannot be written, and using a NULL file pointer crashes the program.

File modes

ModeMeaning
"r"read an existing file
"w"write: create, or empty an existing file
"a"append: write at the end, create if missing
"r+"read and write an existing file
"rb", "wb"the same for binary (non-text) files

Adding to a file

Mode "a" keeps what is in the file and adds at the end, which suits logs and lists that grow each time the program runs:

#include <stdio.h>

int main(void) {
    for (int run = 1; run <= 3; run++) {
        FILE *log = fopen("log.txt", "a");
        if (log == NULL) return 1;
        fprintf(log, "entry %d\n", run);
        fclose(log);
    }
    FILE *f = fopen("log.txt", "r");
    if (f == NULL) return 1;
    char line[50];
    while (fgets(line, sizeof line, f) != NULL) {
        printf("%s", line);
    }
    fclose(f);
    return 0;
}
Output
entry 1
entry 2
entry 3

Why fclose matters

Writing to a file is buffered: the data is collected in memory and written in larger pieces. fclose writes what is left and releases the file. If a program forgets fclose, the end of the data may never reach the file. A program can only have a limited number of files open, too.

Practice exercises

  1. Ask the user for three names and write each on its own line in names.txt.
  2. Write a multiplication table into table.txt, then open the file in the editor.
  3. Run a program with mode "a" several times and watch the file grow.