Home  >  Article  >  Backend Development  >  The difference between printf, sprintf and fprintf in C (code example)

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

藏色散人
藏色散人Original
2019-04-18 15:44:102882browse

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!

Statement:
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