HOME HTML EDITOR C JAVA PHP

C File Handling: Creating and Writing Files

In C, files are treated as a stream of bytes. To manage a file, you must first open a connection to it using a File Pointer. Once the connection is established, you can perform operations like writing text, saving configurations, or logging errors.

1. The FILE Pointer and fopen()

The FILE structure contains information about the file being used. To create or open a file, we use the fopen() function, which takes two arguments: the filename and the mode.

Syntax:

FILE *fptr;
fptr = fopen("filename.txt", "mode");

2. File Opening Modes

The "mode" tells C exactly what you intend to do with the file. To create or write to a file, we primarily use these three modes:

Mode Meaning Behavior
"w" Write Creates a new file. If the file exists, it overwrites all content.
"a" Append Adds data to the end of an existing file without deleting current content.
"w+" Write/Read Creates a file for both reading and writing.

3. Practical Example: Creating and Writing

To write data into a file, we use fprintf() (formatted write) or fputs() (string write). After you are done, you **must** use fclose() to save your changes and free up memory.

#include <stdio.h>

int main() {
    FILE *fptr;

    // Create/Open a file in "w" (write) mode
    fptr = fopen("test.txt", "w");

    // Check if file opened successfully
    if (fptr == NULL) {
        printf("Error opening file!");
        return 1;
    }

    // Write text to the file
    fprintf(fptr, "Hello, this is stored in a file!\n");
    fputs("C programming makes file handling easy.", fptr);

    // Close the file
    fclose(fptr);

    printf("File created and written successfully.");
    return 0;
}

4. Appending Content

If you use "w", your old data is deleted every time you run the program. To keep old data and add new text at the bottom, use the "a" mode.

fptr = fopen("test.txt", "a");
fprintf(fptr, "\nThis line is appended to the existing file.");
fclose(fptr);

5. Critical Safety: The NULL Check

Sometimes, creating a file fails (e.g., you don't have permission to write to a folder or the disk is full). In such cases, fopen() returns NULL. Always check your pointer before using it, or your program will crash with a "Segmentation Fault."

6. Common Pitfalls

Pro Tip: When writing professional software, use "wb" (write binary) if you are saving non-text data like images or encrypted files. This prevents the operating system from messing with newline characters.