printf, sprintf and fprintf are all output statements in C language, and they all output formatted strings. So what are the differences between these three? In this article, we will learn about printf, sprintf and fprintf, and introduce the differences between them. I hope it will be helpful to everyone.
printf
The printf function is used to output text on the standard output device (stdout console) (string/char stream) or value.
Basic syntax
int printf(const char * format,...);
Description:
format provides the format of a text string that will be used on the output device using the formats %s, %d, %f, etc. specifier for output.
...Provide the parameter list that needs to be output.
Return type int returns the total number of characters output on the screen.
Example:
#include<stdio.h> int main() { printf("hello geeksquiz"); printf("\n"); int a=2; printf("%d",a); return 0; }
Output:
##sprintf
sprintf is used to send (copy) formatted text (string/character stream) to a string buffer. Basic syntaxint sprintf(char * str,const char * format,...);
char * str : A character array in which the formatted text will be sent (copied).
●formatProvides formatted text with the help of format specifiers.
●...Provide the parameter list that needs to be output.
● The return type int returns the total number of copied (sent) characters to char * str. Example:#include <stdio.h> int main() { char str[100]; int n; n=sprintf((char*)str,"我的名字是%s, I am %d years old.","Mike",23); printf("Text is: %s\n",str); printf("Total number of copied characters are: %d\n",n); return 0; }
fprintf
fprintf is used to output characters in a file String content, but not output on the stdout console. Basic syntax:int fprintf(FILE * fptr,const char * str,...);
#include<stdio.h> int main() { int i, n=2; char str[50]; //open file sample.txt in write mode FILE *fptr = fopen("sample.txt", "w"); if (fptr == NULL) { printf("无法打开文件"); return 0; } for (i=0; i<n; i++) { puts("输入名称"); gets(str); fprintf(fptr,"%d.%s\n", i, str); } fclose(fptr); return 0; }
Summary:
The difference between printf, sprintf and fprintf is that their output targets are different. printf outputs a data character stream on the stdout console; sprintf sends the data character stream to the specified char buffer; fprintf is used to output string content in a file. The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !The above is the detailed content of What is the difference between printf, sprintf and fprintf in C language. For more information, please follow other related articles on the PHP Chinese website!