C File I/O Operations : fprintf()

The fprintf() function is used to write formatted data into a file. The fprintf() function is similar to printf() function except the first argument which is a file pointer that specifies the file to be written. The syntax of fprintf() function is :
 fprintf(FILE *fp, "format-string", var-list);
Where :
  • fp is file pointer to identify output file.
  • format-string is the C format specifier, just like we used in printf() function.
  • var-list is nothing but the list of variable which needs to be written.
Some of the C format specifier are :

Specifier Used for Example
d or i Signed decimal integer 245
u Unsigned decimal integer 12570
o Unsigned octal 654
x Unsigned hexadecimal integer df12
X Unsigned hexadecimal integer (uppercase) A90
f Decimal floating point, lowercase 345.90
F Decimal floating point, uppercase 345.90
e Scientific notation (mantissa/exponent), lowercase 3.4590e+2
E Scientific notation (mantissa/exponent), uppercase 3.4590E+2
g Use the shortest representation: %e or %f 345.90
G Use the shortest representation: %E or %F 345.90
a Hexadecimal floating point, lowercase -0xd.65fep-2
A Hexadecimal floating point, uppercase -0XD.65FEP-2
c Character z
s String of characters hello
p Pointer address 9dd34500

It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Format tags prototype is :
 %[Flags][Width][.Precision][Length]Specifier
Where the Flags are :

Flags Description
- Left-justifies within the given field width; Right justification is the default (see width sub-specifier).
+ Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a -ve sign.
(space) If no sign is written, a blank space is inserted before the value.
# Used with o, x or X specifiers. The value is preceded with 0, 0x or 0X respectively for values different than zero. Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow then no decimal point is written. Used with g or G the result is the same as with e or E but trailing zeros are not removed.
0 Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier).

Width Description
(number) Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
* The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

.Precision Description
.number For integer specifiers (d, i, o, u, x, X) − precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For e, E and f specifiers: this is the number of digits to be printed after the decimal point. For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. For c type: it has no effect. When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed.
.* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

Length Description
h The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X).
l The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s.
L The argument is interpreted as a long double (only applies to floating point specifiers: e, E, f, g and G).

On success it returns the total numbers of characters written and on the error situation it returns the negative value.

Now lets see some example of it.
#include <stdio.h>

int main() {
  FILE *fp;
  char ch;
  fp = fopen("file.txt", "w");
  fprintf(fp, "%d. %s : %s", 1, "Name", "John snow\n");
  fprintf(fp, "%d. %s : %s", 2, "Name", "Arya Stark\n");
  fprintf(fp, "%d. %s : %s", 3, "Name", "Robb Stark\n");
  fclose(fp);


  // reading the content of file
  fp = fopen("file.txt", "r");
  while((ch=getc(fp)) != EOF) {
    printf("%c", ch);
  }
  fclose(fp);

  return 0;
}
Output :

1. Name : John snow
2. Name : Arya Stark
3. Name : Robb Stark

Now lets see another example of fprintf().
#include <stdio.h>

int main() {
  FILE *fp;
  char str[50], ch;
  int num;

  fp=fopen("file.txt", "w");
  printf("Enter your Name : ");
  scanf("%s", str);
  fprintf(fp, "Name : %s\n", str);
  printf("Your Age : ");
  scanf("%s", str);
  fprintf(fp, "Age : %s\n", str);
  printf("Your City : ");
  scanf("%s", str);
  fprintf(fp, "City : %s\n", str);
  fclose(fp);

  //read contents of file
  printf("\nPrinting contents of file.txt :\n");
  fp = fopen("file.txt", "r");
  while((ch=getc(fp)) != EOF) {
    printf("%c", ch);
  }
  fclose(fp);

  return 0;
}
Output :

Enter your Name : Bruce Wayne
Your Age : 45
Your City : Gotham

Printing contents of file.txt :
Name : Bruce Wayne
Age : 45
City : Gotham

Topics :