EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

fprintf() in C

Home » Software Development » Software Development Tutorials » C Programming Tutorial » fprintf() in C

fprintf()-in-C

Introduction to fprintf() in C

In the C programming language, a library function fprintf which is also known as format print function sends output that is formatted to a stream. Even though it prints the message, it is not possible on stdout console. It is almost similar to normal printf() function except in the fact that it writes data into the file. Moreover, an additional argument is also present in fprintf() function. It is a file pointer that points to the file where the formatted output will be written. The total count of characters that writes to the file will be returned if it is a success. An EOF will be returned if it is failed.

Syntax and Parameters

Below is the syntax of the function fprintf() in the C programming language.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

int fprintf(FILE *stream, const char *format, ...)

Parameters:

  • The stream which is the pointer to a file object that finds the stream.
  • The format is the C string which consists of the text that to be written to the stream. Embedded format tags are also present which can be replaced by the values mentioned in subsequently added arguments and formatted. The prototype of format tags is %[flags][width][.precision][length]specifier.

Return Value:

The total count of characters that writes to the file will be returned if it is a success. An EOF will be returned if it is failed.

The format can be:

1. %d: An integer will be displayed

Example: 9

2. %f: A floating point number will be displayed with a fixed decimal format.

Example: 9.000050

3. %.1f: A floating point number will be displayed with one number after the decimal.

Example: 9.0

4. %e: A floating point number will be displayed in exponential.

Popular Course in this category
C Programming Training (3 Courses, 5 Project)3 Online Courses | 5 Hands-on Projects | 34+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,617 ratings)
Course Price

View Course

Related Courses
C++ Training (4 Courses, 5 Projects, 4 Quizzes)Java Training (40 Courses, 29 Projects, 4 Quizzes)

Example: 9.00045e+1

5. %g: A floating point number will be displayed with a fixed decimal format or exponential based on the number size.

Example: 9.4

Required Header Format:

The required header format in C programming language for the function fprintf is:

#include <stdio.h>

How fprintf() Function Works in C?

  • First, initialize variables based on your requirement.
  • Open the text file in the specified location in write mode using a file pointer.
  • If the file pointer is null, print an error message.
  • If the file pointer is not null, execute the commands based in the requirement.
  • Open the file to check whether the code runs successfully and the output is available in it.

Examples of fprintf() in C

Let us see some sample programs on fprintf() function.

Example #1

C program to Print Names in a File

Code:

#include<stdio.h>
int main()
{
//initialize two integer variables i and n
int i, n=1;
//initialize one character variable
char s[100];
//open the text file in write mode
FILE *filepntr = fopen("C:\\Users\\SCRC_Laptop\\Documents\\C\\sample.txt", "w");
//if file pointer is null, print the statement
if (filepntr == NULL)
{
printf("Sorry. . The file you are trying to open donot exist . . .");
return 0;
}
//if file pointer is not null, execute the for loop
for (i=0; i<n; i++)
{
puts("Enter user name");
gets(s);
fprintf(filepntr,"%d.%s\n", i, s);
}
fclose(filepntr);
return 0;
}

Output:

fprintf() in C-1.1

First, initialize character variable s and two integer variables i and n where n=1. Then, open the text file in the specified location write mode. If the file pointer is null, print “Sorry. The file you are trying to open do not exist . . .”. If the file pointer is not null, execute the for loop that checks whether i<n. As n=1 the loop will execute only one time. Then, the user will be asked to input a user name. This user name will be stored in the file mentioned. It can be seen that on executing the code, a user name will be asked to input. When the file is opened, the name with the index will be displayed as shown below.

fprintf() in C-1.2

Suppose the value of n is changed to 3. Then the user name will be asked three times as depicted in the below figure.

fprintf() in C-1.3

The data in the file will be as shown below.0,1,2 and 3 are the values of i.

fprintf() in C-1.4

Example #2

C Program to Print Student Details in A File.

Code:

#include <stdio.h>
int main()
{
//initialise a file pointer
FILE *filepntr;
//
int rollnum;
char studentname[30];
float mark;
//create a file if not already present
filepntr = fopen("studentinfo.txt", "w+");
if (filepntr == NULL)
{
printf("The file you are trying to open does not exist. . . \n");
return 0;
}
printf("Enter the student roll number : \n");
scanf("%d", &rollnum);
fprintf(filepntr, "roll number= %d\n", rollnum);
printf("Enter the student name: \n");
scanf("%s", studentname);
fprintf(filepntr, "student name= %s\n", studentname);
printf("Enter the mark\n");
scanf("%f", &mark);
fprintf(filepntr, "mark= %.3f\n", mark);
fclose(filepntr);  }

Output:

fprintf() in C-2.1

In this program, first, initialize a file pointer *filepntr. Then, initialize rollnum, student name, mark. Then create a file if not already present. If the file pointer is null, print an error message. Once this is completed, enter the code for inputting the student roll number, student name, and the mark. On executing the code, the user will be asked to input these three values. On successful submission, a file will be created in the folder. The filename of the file created is mentioned in our file pointer.

On opening the file, the details that gave as input will be displayed inside it.

Output-2.2

Example #3

C Program to Print Student Details in a File with Value of i.

#include <stdio.h>
int main()
{
FILE *filepntr;
int i, n=1;
int rollnum;
char studentname[30];
float mark;
filepntr = fopen("studentinfo.txt", "w+");
if (filepntr == NULL)
{
printf("The file you are trying to open does not exist. . . \n");
return 0;
}
for (i=0; i<n; i++)
{
fprintf(filepntr,"%d\n", i);
printf("Enter the student roll number : \n");
scanf("%d", &rollnum);
fprintf(filepntr, "roll number= %d\n", rollnum);
printf("Enter the student name: \n");
scanf("%s", studentname);
fprintf(filepntr, "student name= %s\n", studentname);
printf("Enter the mark\n");
scanf("%f", &mark);
fprintf(filepntr, "mark= %.3f\n", mark);
}
fclose(filepntr);
return 0;
}

Output:

Output-3.1

This program prints the index value along with the details of the student inside the file.

Output-3.2

Recommended Articles

This is a guide to fprintf() in C. Here we also discuss the definition and how fprintf() function work in C along with different examples and its code implementation. You may also have a look at the following articles to learn more –

  1. Stderr in C
  2. Const Pointer in C
  3. Modulus Operator in C
  4. C++ memcpy

C Programming Training (3 Courses, 5 Project)

3 Online Courses

5 Hands-on Projects

34+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
C Programming Tutorial
  • Function
    • Math Functions in C
    • Hashing Function in C
    • Recursive Function in C
    • Power Function in C
    • fputs in C
    • C puts() Function
    • fprintf() in C
    • fseek() in C
    • Stderr in C
    • ASCII Value in C
    • strcat() in C
    • Inline Function in C
    • sizeof() in C
    • Function Prototype in C
    • C ftell()
  • Basic
    • Introduction to C
    • What is C
    • Career in C Programming
    • Advantages of C
    • How to Install C
    • Best C Compilers
    • Data Types in C
    • Variables in C
    • C Keywords
    • C Command
    • Command Line Arguments in C
    • C Literals
    • Constants in C
    • Unsigned Int in C
    • String in C
  • Pointers
    • Pointers in C
    • Null pointer in C
    • Function Pointer in C
    • Double Pointer in C
    • Void Pointer in C
    • Const Pointer in C
    • Dangling Pointers in C
    • Pointer Arithmetic in C
  • Operators
    • C Operators
    • Arithmetic Operators in C
    • Relational Operators in C
    • Assignment Operators in C
    • Logical Operators in C
    • Conditional Operator in C
    • Modulus Operator in C
    • Ternary Operator in C
    • Address Operator in C
    • Unary Operator in C
    • Operators Precedence in C
    • Left Shift Operator in C
  • Control Statement
    • Control Statements in C
    • If Statement in C
    • If-else Statement in C
    • Else if Statement in C
    • Nested if Statement in C
    • #else in C
    • Structure Padding in C
    • Nested Structure in C
    • Continue Statement in C
    • Break Statement in C
    • Switch Statement in C
    • Goto Statement in C
  • Loops
    • Loops in C
    • For Loop in C
    • While Loop in C
    • Do While Loop in C
    • Nested Loop in C
    • Infinite Loop in C 
  • Array
    • Arrays in C Programming
    • 2-D Arrays in C
    • 3D Arrays in C
    • Multidimensional Array in C
    • Array Functions in C
    • Strings Array in C
  • Sorting
    • Sorting in C
    • Heap Sort in C
  • Advanced
    • Constructor in C
    • Encapsulation in C
    • C Storage Classes
    • Static Keyword in C
    • File Handling in C
    • Queue in C
    • Hexadecimal in C 
    • typedef in C
    • Memory Allocation in C
    • Linked List in C
    • Volatile in C
    • Tokens in C
    • Expression in C
    • Regular Expression in C
    • Error Handling in C
    • Types of Errors in C
    • Preprocessor in C
    • Preprocessor Directives in C
    • fscanf() in C
    • #Pragma in C
    • #ifndef in C
    • #undef in C
    • Macros in C
  • C programs
    • Patterns in C Programming
    • Star Patterns in C
    • Number Patterns in C
    • Swapping in C
    • Reverse Number in C
    • Palindrome in C Program
    • Factorial in C
    • Fibonacci Series in C
    • Square Root in C
    • Random Number Generator in C
    • Prime Numbers in C
    • Escape Sequence in C
    • Reverse String in C
    • Leap Year Program in C
    • Anagram Program in C
    • Strong Number in C
    • String Concatenation in C
    • C Programming Matrix Multiplication
    • Decimal to Octal in C
    • Expression Evaluation in C
    • Decimal to Hexadecimal in C
  • Interview question
    • C Programming Interview Questions

Related Courses

C Programming Training Course

C++ Training Course

Java Training Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C Programming Training (3 Courses, 5 Project) Learn More