Welcome to this comprehensive guide on the fprintf() function in C programming! This function is a powerful tool for writing formatted output to a stream. By the end of this lesson, you'll be able to use it confidently in your projects. 🎯
fprintf() FunctionThe fprintf() function is a part of the stdio.h library in C. It stands for "formatted print to file," and as the name suggests, it allows you to write formatted data to a file or any other output stream. 📝
Here's a simple syntax for fprintf():
#include <stdio.h>
int fprintf(FILE *stream, const char *format, ...);The function takes three arguments:
stream: A pointer to a FILE structure, which represents the output stream (file, stdout, or stderr).format: A string that contains placeholders for the data you want to write, using % followed by a format specifier.Let's see an example of writing to a file:
#include <stdio.h>
int main() {
FILE *file;
file = fopen("example.txt", "w"); // Open the file in write mode
if (file == NULL) {
printf("Failed to open file.\n");
return 1;
}
fprintf(file, "Hello, World!\n"); // Write to the file using fprintf()
fclose(file); // Close the file
return 0;
}In this example, we create a file named example.txt and write "Hello, World!" to it using the fprintf() function. ✅
The fprintf() function can handle various data types, including integers, floating-point numbers, characters, and strings. Here's how to format each data type:
%d: Signed decimal integer (e.g., int)%i: Same as %d (C99 and later)%u: Unsigned decimal integer (e.g., unsigned int)%o: Octal integer (base 8)%x or %X: Hexadecimal integer (base 16, lowercase or uppercase)%f: Floating-point number (e.g., float or double)%e or %E: Scientific notation (e.g., 6.02e23)%g or %G: Choose between %e and %f, whichever is more efficient%c: Character (e.g., char)%s: String (array of characters)#include <stdio.h>
int main() {
double pi = 3.14159265358979323846;
int apples = 20;
fprintf(stdout, "The value of π is approximately %f.\n", pi);
fprintf(stdout, "We have %d apples in the basket.\n", apples);
return 0;
}In this example, we write the value of π using the %f format specifier and the number of apples using the %d specifier. ✅
Which function is used for writing formatted output to a file in C programming?
With this lesson, you now have a solid understanding of the fprintf() function in C programming. Happy coding, and keep exploring the fascinating world of C! 💡