HOME HTML EDITOR C JAVA PHP

C Write to Files: Storing Data Permanently

Writing to a file involves three distinct steps: Opening the file in a writable mode, Sending the data through a stream, and Closing the file to flush the buffer and save changes.

1. The Primary Writing Functions

C provides different functions depending on whether you want to write formatted text, simple strings, or single characters.

2. Implementation Example

Here is how you would write structured data into a text file named data.txt:

#include <stdio.h>

int main() {
    FILE *fptr;
    int score = 95;
    char name[] = "John Doe";

    // Open for writing ("w")
    fptr = fopen("data.txt", "w");

    if (fptr != NULL) {
        // Writing a formatted string
        fprintf(fptr, "Student: %s\nScore: %d", name, score);

        // Closing is mandatory to ensure data is saved
        fclose(fptr);
        printf("Data written successfully.");
    } else {
        printf("Unable to create file.");
    }

    return 0;
}

3. The Difference Between "w" and "a"

Understanding the file mode is critical. Choosing the wrong one can result in losing existing data.

Mode Action Risk Level
"w" (Write) Deletes old content and starts fresh. High (Data loss)
"a" (Append) Keeps old content; adds new data to the end. Low (Safe)

4. Buffering and fclose()

When you write to a file, C doesn't always send the data to the disk immediately. It stores it in a small "buffer" in RAM to improve speed. fclose() performs a "flush," forcing any remaining data in the buffer to be written to the physical storage device.

5. Writing Large Data (fwrite)

If you need to write an entire array or a struct to a file at once, professional C developers use fwrite(). This writes data in binary format, which is much faster and takes up less space than text.

// Writing an array of integers in one go
int numbers[] = {1, 2, 3, 4, 5};
fwrite(numbers, sizeof(int), 5, fptr);
Pro Tip: Always use \n at the end of your fprintf or fputs calls if you want the next piece of data to appear on a new line. Unlike puts() in the console, fputs() does not add a newline automatically!