Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c
filing
output
formatted printing
stdout

How to use a printing formatted data to file using fprintf() in C

Educative Answers Team

In C, the fprintf() function is used to print formatted data to a file.

svg viewer

Syntax

The general syntax of fprintf() is:

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

Parameters

  • stream: Pointer to the FILE object where data is to be printed

  • format: This contains the data to be printed, written in a particular format using format specifiers

A format specifier is a unique character which is used to specify the data type of the value being read.

The format specifier follows the following prototype:

 %[flags][width][.precision][length]specifier
svg viewer

Return Value

If the function successfully executes, it returns the total number of characters written to the file. If an error occurs, a negative number is returned.

Example

The following examples will help clarify the use of the fprintf() function:

#include<stdio.h>

int main() {
    FILE * stream;

    stream = fopen("/file.txt", "w");
    // Printing a string
    char str[20] = "Hello World!";
    int x = fprintf(stream, "%s", str);  
    printf("\n %d characters successfully written to the file\n\n", x);

    // Printing an integer value
    int age = 22;
    x = fprintf(stream, "%d", age);  
    printf("\n %d characters successfully written to the file\n\n", x);
    fclose(stream);
    return 0;
}

RELATED TAGS

c
filing
output
formatted printing
stdout
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring