printf(), sprintf() and fprintf() in C


printf()

The function printf() is used to print the message along with the values of variables.

Here is the syntax of printf() in C language,

printf(const char *str, ...);

Here is an example of printf() in C language,

Example

 Live Demo

#include<stdio.h>
int main() {
   int a = 24;
   printf("Welcome! 
");    printf("The value of a : %d",a);    getchar();    return 0; }

Output

Welcome!
The value of a : 24

sprintf()

The function sprintf() is also known as string print function. It do not print the string. It stores the character stream on char buffer. It formats and stores the series of characters and values in an array.

Here is the syntax of sprintf() in C language,

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

Here is an example of sprintf() in C language,

Example

 Live Demo

#include<stdio.h>
int main() {
   char buf[20];
   int x = 15, y = 25, z;
   z = x + y;
   sprintf(buf, "Sum of values : %d", z);
   printf("%s", buf);
   return 0;
}

Output

Sum of values : 40

fprintf ()

The function fprintf() is known as format print function. It writes and formats the output to a stream. It is used to print the message but not on stdout console.

Here is the syntax of fprintf() in C language,

int fprintf(FILE *fptr, const char *str, ...);

Here is an example of fprintf() in C language,

Example

 Live Demo

#include<stdio.h>
int main() {
   int i, x = 4;
   char s[20];
   FILE *f = fopen("new.txt", "w");
   if (f == NULL) {
      printf("Could not open file");
      return 0;
   }
   for (i=0; i<x; i++) {
      puts("Enter text");
      gets(s);
      fprintf(f,"%d.%s
", i, s);    }    fclose(f);    return 0; }

Output

Enter text
Hello world!
Enter text
Demo

The output will modify the “new.txt” file. The following text is the modified text of the file.

0,Hello world!
1,Demo

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 24-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements