0
0
Cprogramming~5 mins

Writing to files in C

Choose your learning style9 modes available
Introduction

Writing to files lets your program save information so you can use it later or share it with others.

Saving user settings so they stay after the program closes.
Logging events or errors while a program runs.
Creating reports or data files from program results.
Storing game progress or scores.
Exporting data to share with other programs or people.
Syntax
C
FILE *file_pointer;
file_pointer = fopen("filename.txt", "w");
if (file_pointer != NULL) {
    fprintf(file_pointer, "text to write\n");
    fclose(file_pointer);
}

fopen opens a file. The "w" means write mode, which creates or overwrites the file.

fprintf writes formatted text to the file, like printf but for files.

Examples
Open a file named data.txt for writing, write a line, then close it.
C
FILE *fp = fopen("data.txt", "w");
if (fp != NULL) {
    fprintf(fp, "Hello, file!\n");
    fclose(fp);
}
Open log.txt in append mode to add text at the end without erasing existing content.
C
FILE *fp = fopen("log.txt", "a");
if (fp != NULL) {
    fprintf(fp, "New log entry\n");
    fclose(fp);
}
Sample Program

This program opens a file named example.txt for writing, writes two lines, closes the file, and prints a success message.

C
#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "w");
    if (file == NULL) {
        printf("Error opening file.\n");
        return 1;
    }
    fprintf(file, "This is a line of text.\n");
    fprintf(file, "Writing to files is easy!\n");
    fclose(file);
    printf("Data written to example.txt successfully.\n");
    return 0;
}
OutputSuccess
Important Notes

Always check if fopen returns NULL to avoid errors when the file can't be opened.

Remember to close the file with fclose to save changes and free resources.

Using "w" mode deletes existing file content; use "a" to add without deleting.

Summary

Use fopen with "w" to open a file for writing (creates or overwrites).

Use fprintf to write text to the file.

Always close the file with fclose when done.