Write Formatted Text to a File in C
To write formatted text to a file in C, you can use functions like fprintf() or combine sprintf() with fputs(). These functions allow you to format data similarly to printf() and write the resulting string directly into a file.
Example 1: Writing Formatted Text Using fprintf()
In this example, we will open a file named output.txt, write a formatted string that includes a name, age, and score using fprintf(), and then close the file.
main.c
#include <stdio.h>
int main() {
// Open file in write mode
FILE *fp = fopen("output.txt", "w");
if (fp == NULL) {
perror("Error opening file");
return 1;
}
// Variables for formatted output
char name[] = "John";
int age = 25;
float score = 87.5;
// Write formatted text to the file
fprintf(fp, "Name: %s, Age: %d, Score: %.1f\n", name, age, score);
// Close the file
fclose(fp);
return 0;
}
Explanation:
FILE *fp = fopen("output.txt", "w");opens the fileoutput.txtin write mode. If the file does not exist, it is created.char name[] = "John";,int age = 25;, andfloat score = 87.5;declare and initialize variables to be written.fprintf(fp, "Name: %s, Age: %d, Score: %.1f\n", name, age, score);formats the string and writes it into the file. Here,%sis for a string,%dfor an integer, and%.1ffor a float with one decimal precision.fclose(fp);closes the file, ensuring that the data is properly saved.
Output:
Name: John, Age: 25, Score: 87.5
Example 2: Writing Formatted Text Using sprintf() and fputs()
In this example, we will use sprintf() to format a string and store it in a buffer, then open a file named output2.txt and write the formatted string using fputs().
main.c
#include <stdio.h>
int main() {
// Buffer to hold the formatted string
char buffer[100];
// Variables for formatting
char name[] = "Alice";
int year = 2025;
// Format the string and store it in buffer
sprintf(buffer, "User: %s, Year: %d", name, year);
// Open file in write mode
FILE *fp = fopen("output2.txt", "w");
if (fp == NULL) {
perror("Error opening file");
return 1;
}
// Write the formatted string from buffer to the file
fputs(buffer, fp);
// Close the file
fclose(fp);
return 0;
}
Explanation:
char buffer[100];declares a character array to hold the formatted string.sprintf(buffer, "User: %s, Year: %d", name, year);formats the string using the variables and stores it inbuffer.FILE *fp = fopen("output2.txt", "w");opens the fileoutput2.txtin write mode, creating it if it doesn’t exist.fputs(buffer, fp);writes the string stored inbufferto the file.fclose(fp);closes the file, ensuring the data is saved correctly.
Output:
User: Alice, Year: 2025
Conclusion
In this tutorial, we demonstrated two approaches to writing formatted text to a file in C: using fprintf() for direct formatted output and using a combination of sprintf() with fputs() for more flexible string handling.
