C Write to Files

C Write to Files: Saving Your Data

Once you have successfully created or opened a file using fopen(), the next step is to write data into it. C provides several functions in the <stdio.h> library for writing text and data to files.

The most common functions for writing text files are fprintf(), fputs(), and fputc(). Let's explore how to use them to save application states, user inputs, or generate comprehensive reports.


1. Writing Formatted Output with fprintf()

The fprintf() function is the file equivalent of printf(). It allows you to write formatted strings, integers, floats, and other variables directly to a file. It is incredibly versatile and is the go-to function for most file-writing tasks.

Syntax:

fprintf(file_pointer, "format string", variables...);

Example: Writing variables to a file

fprintf() Example

#include <stdio.h>

int main() { FILE *fptr; fptr = fopen("report.txt", "w"); if (fptr == NULL) { printf("Failed to open file.\n"); return 1; } char name[] = "Alice"; int score = 95; // Writing formatted text to the file fprintf(fptr, "Student Name: %s\n", name); fprintf(fptr, "Final Score: %d\n", score); printf("Data written successfully!\n"); fclose(fptr); return 0; }

Note: If you run this code, it creates report.txt and inserts the text "Student Name: Alice" followed by "Final Score: 95" on the next line.


2. Writing Strings with fputs()

If you only need to write a simple string to a file without any formatting (like replacing %d with numbers), fputs() is a slightly faster and safer alternative to fprintf().

Example:

fputs() Example

#include <stdio.h>

int main() { FILE *fptr = fopen("greetings.txt", "w"); if (fptr != NULL) { fputs("Hello, World!\n", fptr); fputs("Welcome to C File Handling.\n", fptr); fclose(fptr); } return 0; }


3. Appending Data vs. Overwriting

It is critical to remember how file modes impact your write operations:

Append Example:

If you want to create an activity log for your software, you should always use the append mode "a".

Append Mode Example

#include <stdio.h>

int main() { // Using "a" mode to preserve existing logs FILE *fptr = fopen("activity_log.txt", "a"); if (fptr != NULL) { fprintf(fptr, "User logged in.\n"); fclose(fptr); } return 0; }


Exercise

?

Which function is the best choice if you need to write a mixture of text, integers, and floating-point variables to a file?