The difference between printf, sprintf and fprintf in C (code example)

藏色散人
Release: 2019-04-18 15:44:10
Original
2901 people have browsed it

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, ...);
Copy after login

Example:

#include<stdio.h> 
int main() 
{ 
   printf("hello geeksquiz"); 
   return 0; 
}
Copy after login

Output:

hello geeksquiz
Copy after login

sprintf:

Syntax:

int sprintf(char *str, const char *string,...);
Copy after login

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; 
}
Copy after login

Output:

Sum of 10 and 20 is 30
Copy after login

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, ...);
Copy after login

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; 
}
Copy after login
输入: GeeksforGeeks
       GeeksQuiz
输出:  sample.txt file now having output as 
0. GeeksforGeeks
1. GeeksQuiz
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!