Writing text data to files on disk in C involves opening a file stream pointer (FILE *) via fopen(), writing strings using fputs() or fprintf(), and closing the handle with fclose() to flush OS write buffers.

File Writing C Code Example

file_write.cc
#include <stdio.h>
 
int main(void) {
    // Open file in write mode ("w" overwrites, "a" appends)
    FILE *fp = fopen("output.txt", "w");
 
    if (fp == NULL) {
        perror("Error opening file for writing");
        return 1;
    }
 
    // 1. Write plain string via fputs()
    fputs("Lynxbee Systems Engineering\n", fp);
 
    // 2. Write formatted string via fprintf()
    int active_cores = 8;
    fprintf(fp, "CPU Cores Detected: %d\n", active_cores);
 
    // Flush and close file handle
    fclose(fp);
    printf("File written successfully.\n");
 
    return 0;
}