fprintf Function

Prints formatted text to a stream.

Include

<stdio.h>

Prototype

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

Arguments

stream pointer to the stream in which to output data
format format control string
... optional arguments; see “Remarks”

Return Value

Returns number of characters generated or a negative number if an error occurs.

Remarks

The format argument has the same syntax and use that it has in printf.

Example

#include <stdio.h> /* for fopen, fclose, */
                   /* fprintf, printf,   */
                   /* FILE, NULL         */

int main(void)
{
  FILE *myfile;
  int y;
  char s[]="Print this string";
  int x = 1;
  char a = '\n';
  if ((myfile = fopen("afile", "w")) == NULL)
    printf("Cannot open afile\n");
  else
  {
    y = fprintf(myfile, "%s %d time%c", s, x, a);

    printf("Number of characters printed "
           "to file = %d",y);

    fclose(myfile);
  }
}

Example Output

Number of characters printed to file = 25

Contents of afile:

Print this string 1 time