Lesson 84 +10 XP

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
");
        return 1;
    }
    fprintf(file, "Hello World!
");
    fputs("Another line
", file);
    fclose(file);
    return 0;
}

fprintf works like printf

Same specifiers, but the file pointer comes first:


c
fprintf(file, "%d items
", 42);

fputs writes a string + newline


c
fputs("hello
", 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.