Lesson 84 +10 XP

Writing to Files

Writing to Files

Once a file is open for writing, fprintf writes formatted text into it.

fputs and fprintf

#include <stdio.h>

int main() {
    FILE *file = fopen("file.txt", "w");
    if (file == NULL) {
        printf("Unable to open file\n");
        return 1;
    }
    fprintf(file, "Hello World!\n");
    fputs("Another line\n", file);
    fclose(file);
    return 0;
}

fprintf works like printf

Same specifiers, but the file pointer comes first:

fprintf(file, "%d items\n", 42);

fputs writes a string + newline

fputs("hello\n", file);

Appending with "a"

Using "a" adds to the end instead of wiping the file.

TL;DR

  • fprintf(file, format, ...) writes formatted text.
  • fputs(str, file) writes a string.
  • Open with "w" to overwrite, "a" to append.
  • Always close the file when done.