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.
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.
fprintf(file_pointer, "format string", variables...);
#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.
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().
#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; }
It is critical to remember how file modes impact your write operations:
"w" (Write): Opens the file and starts writing from the absolute beginning. Any previous content is deleted."a" (Append): Opens the file and moves the invisible "cursor" to the very end. Any fprintf or fputs commands will add data after the existing content, preserving what was already there.If you want to create an activity log for your software, you should always use the append mode "a".
#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; }
Which function is the best choice if you need to write a mixture of text, integers, and floating-point variables to a file?