Home >Backend Development >C#.Net Tutorial >The difference between printf, sprintf and fprintf in C (code example)
This article mainly introduces the differences between printf, sprintf and fprintf in C language. I hope it will be helpful to friends in need!
printf:
The printf function is used to print character stream data on the stdout (standard output) console.
Syntax:
int printf(const char* str, ...);
Example:
#include<stdio.h> int main() { printf("hello geeksquiz"); return 0; }
Output:
hello geeksquiz
sprintf:
Syntax:
int sprintf(char *str, const char *string,...);
sprintf is used to print formatted text (string/character stream) to a string buffer.
Example:
#include<stdio.h> int main() { char buffer[50]; int a = 10, b = 20, c; c = a + b; sprintf(buffer, "Sum of %d and %d is %d", a, b, c); printf("%s", buffer); return 0; }
Output:
Sum of 10 and 20 is 30
fprintf:
fprintf is used to print a string in a file content, but does not print on the stdout (standard output) console.
int fprintf(FILE *fptr, const char *str, ...);
Example:
#include<stdio.h> int main() { int i, n=2; char str[50]; FILE *fptr = fopen("sample.txt", "w"); if (fptr == NULL) { printf("Could not open file"); return 0; } for (i=0; i<n; i++) { puts("Enter a name"); gets(str); fprintf(fptr,"%d.%s\n", i, str); } fclose(fptr); return 0; }
输入: GeeksforGeeks GeeksQuiz 输出: sample.txt file now having output as 0. GeeksforGeeks 1. GeeksQuiz
Related recommendations: "C Tutorial"
The above is the detailed content of The difference between printf, sprintf and fprintf in C (code example). For more information, please follow other related articles on the PHP Chinese website!