w3resource

C fprintf() function

C library function - fprintf()

The fprintf() function is used for printing information to the screen.

Syntax:

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

Parameters:

Name Description
stream Identifies an address for a file descriptor, which is an area of memory associated with an input or output stream.
format The format argument is a string containing C language conversion specifications. The conversion specification specifies the notation, alignment, significant digits, field width, and other aspects of the output format. To represent non-printing characters, such as newlines and tabs, the format string may contain escape characters. Below are the details.
additional arguments Depending on the format string, the function may require additional arguments.

Format strings specify notation, alignment, significant digits, field width, and other aspects of output formats. It can contain ordinary alphanumeric characters; along with escape characters, conversion specifiers, and other characters, organized as shown below:

Flags

The alignment of the output can be controlled using any of the optional flags listed below:

Character Description Example
A plus sign (+) Always prints a sign character (+ or -). %+7.2d
A minus sign (-) Left-justifies the converted argument in its field. %-7.2d
Zero (0) Pad with zeros rather than spaces. %07.2d
Digits (field width) A digit string specifying the minimum number of digits to be printed. %6f
Digits (precision) A digit string including a period (.) specifying the number of digits to be printed to the right of the decimal point. %7.2f

Field Width and Precision Specifications

By including these options in the format string, you can control the width and precision of the output:

Character Description Example
Field width A digit string specifying the minimum number of digits to be printed. %5f
Precision A digit string including a period (.) specifying the number of digits to be printed to the right of the decimal point. %5.2f

Conversion Characters

The conversion characters specify the output notation:

Specifier Description
%c Single character
%d Decimal notation (signed)
%e Exponential notation (using a lowercase e as in 3.1415e+00)
%E Exponential notation (using an uppercase E as in 3.1415E+00)
%f Fixed-point notation
%g The more compact of %e or %f, as defined in [2]. Insignificant zeros do not print.
%G Same as %g, but using an uppercase E
%o Octal notation (unsigned)
%s String of characters
%u Decimal notation (unsigned)
%x Hexadecimal notation (using lowercase letters a-f)
%X Hexadecimal notation (using uppercase letters A-F)

Escape Characters

The following tables describe the non-alphanumeric characters found in format specification strings:

Character Description
\n New line
\t Horizontal tab
\b Backspace
\r Carriage return
\f Form feed
\\ Backslash
'' or '' (two single quotes) Single quotation mark

Return value

  • If successful, the total number of characters written is returned otherwise, a negative number is returned.

Example: fprintf() function

Following example create a file test.txt with the uses of fprintf() function.

#include <stdio.h>
int count [12] = {1}; 
int main(void) {
  int i, j;
  i = 100;
  FILE * stream;
  stream = fopen("test.txt", "w");
  fprintf(stream,"** Input text with integers using fprintf(): **");
  fprintf(stream,"\nTo output an integer, use %%d in the format string.");
  int num_of_employees = 203;
  fprintf(stream,"\nNumber of employees: %d ", num_of_employees); 
  fprintf(stream,"\nWe can specify the field width (i.e. how many 'spaces' the item prints in). Default is right-justification.");
  num_of_employees = 50;
  fprintf(stream,"\nNumber of employees: %8d ", num_of_employees); 
  fprintf(stream,"\nTo left justify, use a negative number in the field width:");
  fprintf(stream,"\nNumber of employees: %-8d ", num_of_employees); 
  fprintf(stream,"\nThe minimum number of characters required to print the item will be used if the field width is too small or left unspecified.");
  fprintf(stream, "\nNumber of employees: %2d", num_of_employees);
  fprintf(stream,"\n\n** Input text with Floating-point using fprintf(): **");
  double sale_amt = 345.27;
  fprintf(stream,"\nTo print floating point values in fixed notation, use the %%f modifier:");
  fprintf(stream,"\nYour sale amount is $%f today\n", sale_amt);
  fprintf(stream,"\nUse %e for exponential notation:");
  fprintf(stream,"Sale amount is %e today\n", sale_amt);
  fprintf(stream,"\nFurthermore, you can control the decimal precision, which refers to the number of places after the decimal point:");
  fprintf(stream,"\nThe output will be rounded to the appropriate number of decimal places, if necessary.");
  fprintf(stream,"\nSale amount is $%.2f today\n", sale_amt);
  fprintf(stream,"\nThe width of the field can also be controlled, as with integers:");
  fprintf(stream,"\nSale amount is $%9.2f today\n", sale_amt);
  fprintf(stream,"\n** Printing characters and strings: **");
  fprintf(stream,"\nFor characters, use the formatting specifier %%c. Default field size is 1 character");
  char ch = 'A';
  fprintf(stream,"\n%c%c%c\n", '*', ch, '*');
  fprintf(stream,"\nUse %%s%%s for printing strings. The same rules apply to field widths as they do to integers:");
  fprintf(stream,"\n%s%10s%-10sEND\n", "Red", "Green", "White"); 
 
  fclose(stream);
  FILE * fp;
  int c;
  fp = fopen("test.txt", "r");
  while (1) {
    c = fgetc(fp);
    if (feof(fp)) {
      break;
    }
    printf("%c", c);
  }
  fclose(fp);
  return (0);
}

Output:

Output of the said file data:
** Input text with integers using fprintf(): **
To output an integer, use %d in the format string.
Number of employees: 203
We can specify the field width (i.e. how many 'spaces' the item prints in). Default is right-justification.
Number of employees:       50
To left justify, use a negative number in the field width:
Number of employees: 50
The minimum number of characters required to print the item will be used if the field width is too small or left unspecified.
Number of employees: 50

** Input text with Floating-point using fprintf(): **
To print floating point values in fixed notation, use the %f modifier:
Your sale amount is $345.270000 today

Use 3.204834e-317 for exponential notation:Sale amount is 3.452700e+002 today

Furthermore, you can control the decimal precision, which refers to the number of places after the decimal point:
The output will be rounded to the appropriate number of decimal places, if necessary.
Sale amount is $345.27 today

The width of the field can also be controlled, as with integers:
Sale amount is $   345.27 today

** Printing characters and strings: **
For characters, use the formatting specifier %c. Default field size is 1 character
*A*

Use %s%s for printing strings. The same rules apply to field widths as they do to integers:
Red     GreenWhite     END

C Programming Code Editor:

Previous C Programming: C tmpnam()
Next C Programming: C sprintf()



Follow us on Facebook and Twitter for latest update.