Demonstrates the fprintf() function. - C File

C examples for File:File Write

Description

Demonstrates the fprintf() function.

Demo Code

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

void clear_kb(void);

int main( void )
{
    FILE *fp;//from w w  w  .  ja v a 2s .  c  om
    float data[5];
    int count;
    char *filename = "text.txt";

    puts("Enter 5 floating-point numerical values.");

    for (count = 0; count < 5; count++)
        scanf("%f", &data[count]);

    clear_kb();

    if ( (fp = fopen(filename, "w")) == NULL)
    {
        fprintf(stderr, "Error opening file %s.", filename);
        exit(1);
    }

    for (count = 0; count < 5; count++){
        fprintf(fp, "\ndata[%d] = %f", count, data[count]);
        fprintf(stdout, "\ndata[%d] = %f", count, data[count]);
    }
    fclose(fp);
    printf("\n");
    return 0;
}

void clear_kb(void)/* Clears stdin of any waiting characters. */
{
    char junk[80];
    gets_s(junk);
}

Result


Related Tutorials