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

C
#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:

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

fputs writes a string + newline

C
fputs("hello\n", file);

Appending with &quot;a&quot;

Using &quot;a&quot; 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 &quot;w&quot; to overwrite, &quot;a&quot; to append.
  • Always close the file when done.