fprintf() function in C language with Example

Here, we are going to learn about the fprintf() function of library header stdio.h in C language with its syntax, example.
Submitted by Souvik Saha, on January 09, 2019

fprintf() function in C

Prototype:

    int fprintf(FILE *filename, const char *string, . . . .);

Parameters:

    FILE *filename, const char *string etc.

Return type: int

Use of function:

Like printf() function, fprintf() function is used to write the argument statement string on the file stream. Through the fprintf() function we write or store the values with the string. The prototype of the function fprintf() is: int fprintf(FILE *filename, const char *string, . . . .);

Here string is the user defined string along with the existing data types (likes int, float, char etc).

fprintf() example in C

#include <stdio.h>
#include <stdlib.h>

int main()
{
    //Initialize the file pointer
    FILE* f;
    char ch[100];

    // open the file for read and write operation
    if ((f = fopen("includehelp.txt", "r+")) == NULL) {
        //if the file does not exist print the string
        printf("Cannot open the file...");
        exit(1);
    }

    for (int i = 0; i < 10; i++) {
        //enter the strings with values in the file
        fprintf(f, "The count number is %d\n", i + 1);
    }
    fclose(f);

    // open the file for read and write operation
    if ((f = fopen("includehelp.txt", "r+")) == NULL) {
        //if the file does not exist print the string
        printf("Cannot open the file...");
        exit(1);
    }

    printf("File content is--\n");
    printf("\n...............print the strings..............\n\n");
    while (!feof(f)) {
        //takes the first 100 character in the character array
        fgets(ch, 100, f);
        //and print the strings
        printf("%s", ch);
    }
    //close the file
    fclose(f);

    return 0;
}

Output

fprintf example in c

C stdio.h Library Functions Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.