OverIQ.com

fprintf() Function in C

Last updated on July 27, 2020


Formatted File Input and Output #

Up to this point, we have seen how to read and write characters and string to and from the file. In the real world, the data consists of many different types. In this chapter, we will learn how we can input and output data of different types in a formatted way. We use formatted input and output when we want to read or write data in a particular format.

fprintf() function #

Syntax: int fprintf(FILE *fp, const char *format [, argument, ...] );

The fprintf() function is same as printf() but instead of writing data to the console, it writes formatted data into the file. Almost all the arguments of fprintf() function is same as printf() function except it has an additional argument which is a file pointer to the file where the formatted output will be written. On success, it returns the total number of characters written to the file. On error, it returns EOF.

The following program demonstrates how to use fprintf() function.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include<stdio.h>
#include<stdlib.h>

int main()
{
    FILE *fp;
    char name[50];
    int roll_no, chars, i, n;
    float marks;

    fp = fopen("records.txt", "w");

    if(fp == NULL)
    {
        printf("Error opening file\n");
        exit(1);
    }

    printf("Testing fprintf() function: \n\n");

    printf("Enter the number of records you want to enter: ");
    scanf("%d", &n);

    for(i = 0; i < n; i++)
    {
        fflush(stdin);
        printf("\nEnter the details of student %d \n\n", i +1);

        printf("Enter name of the student: ");
        gets(name);

        printf("Enter roll no: ");
        scanf("%d", &roll_no);

        printf("Enter marks: ");
        scanf("%f", &marks);

        chars = fprintf(fp, "Name: %s\t\tRoll no: %d\t\tMarks: %.2f\n",
            name, roll_no, marks);
       printf("\n%d characters successfully written to the file\n\n", chars);
    }

    fclose(fp);
    return 0;
}

Expected Output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
Testing fprintf() function:

Enter the number of records you want to enter: 5

Enter the details of student 1

Enter name of the student: Tina
Enter roll no: 1
Enter marks: 45

37 characters successfully written to the file

Enter the details of student 2

Enter name of the student: Nina
Enter roll no: 5
Enter marks: 89

37 characters successfully written to the file

Enter the details of student 3

Enter name of the student: Tim
Enter roll no: 2
Enter marks: 49

36 characters successfully written to the file

Enter the details of student 4

Enter name of the student: Jim
Enter roll no: 8
Enter marks: 41

36 characters successfully written to the file

Enter the details of student 5

Enter name of the student: King
Enter roll no: 9
Enter marks: 59

37 characters successfully written to the file

How it works:

In line 6, a structure pointer variable fp is declared of type struct FILE.

In line 7, an array of characters name of size 50 is declared.

In line 8, four variables namely roll_no, chars, i and n of type int are declared.

In line 9, a variable marks of type float is declared.

In line 11, fopen() function is called with two arguments namely "records.txt" and "w". On success, it returns a pointer to file records.txt and opens the file records.txt in write-only mode. On failure, it returns NULL.

In line 13-17, if statement is used to test the value of fp. If it is NULL, printf() statement prints the error message and program terminates. Otherwise, the program continues with the statement following the if statement.

In line 19, a printf() statement prints "Testing fprintf() function: \n\n" to the console.

In line 21-22, the program asks the user to enter the number of students whose records he wants to enter.

In lines 24-41, a for loop asks the user to enter three pieces of information name, roll_no and marks of the respective students. In line 26, we are flushing (removing) the contents of the standard input, this line is necessary otherwise gets() function in line 30 will read the newline character (entered while asking the number of students) and will not wait for the user to enter the name of the student.

In line 38, fprintf() function is called along with 5 arguments to write formatted data to the file. If the data has been written successfully to the file, it returns the number of characters written to the file, which is then assigned to variable chars. In line 40, a printf() statement prints the total number of characters written to the file by the previous call of fprintf() function. The loop will keep asking for more records of students until i < n. As soon as n becomes greater than i, the control comes out of the for loop.

In line 43, fclose() function closes the file.