C programming fprintf stdio.h


The C <stdio.h> fprintf function outputs the data in a stream.The declaration of the function is shown below.

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

Parameters:
stream -The stream to which the data is to be outputted

format -The data or string to be outputted to the stream and it specify how the subsequent arguments are evaluated but otherwise ignored.

-The third argument-ellipsis-can consist of the conversion specifier.

Return type
int -Returns the number of character transmitted or a negative value if the output or encoding error occur.

***Note the first argument stream can be FILE* type or stdout or stderr.

Link: C fopen stdio.h

Code example

FILE *fp=fopen(“text.txt” , “w+” );

int numberOfCharTransmitted ;

numberOfCharTransmitted=fprintf( stdout , “New string ” ); //printing the string “New string ” to console

fprintf( “\nNumber of character transmitted=%i” , numberOfCharTransmitted );

fprintf( fp , “New string “); //printing the string “New string ” to text.txt file

flcose( fp );

Output,

New string
Number of character transmitted=11

If you count the number of characters in the string “New string ” it consist of 11 characters which is the returned value of the fprintf() function.

To check the content of the text.txt file ,try opening the file you will find the string “New string “.

Link: C fclose stdio.h





Some points to note

i)Conversion specifier rule

The conversion specifier rule still applies if the specifier are used on the arguments lists.Consider the code below.

Code example

int numberOfCharTransmitted ;

float hr=23 ;
double min=45 , sec=34.56 ;

numberOfCharTransmitted=fprintf( stdout , “The time is :%f::%lf:&lf” , hr , min , sec );

fprintf( “\nNumber of character transmitted=%i” , numberOfCharTransmitted );

Output in Visual Studio,

The time is :23.000000::45.000000:34.560000
Number of character transmitted=43

Another code example is shown below.

Code example

wchar_t wstr[]=L”Wide string” ;
char str[]=”Normal string;”

fprintf( stdout , “pi=%.4f” , 4*atan(1.0) );

fprintf( stdout , “\n%ls” , wstr );
fprintf( stdout , “\n%s” , str );
fprintf( stderr , “\nAn error occurred!!” , wstr );

Output in Visual Studio,

pi=3.1416
Wide string
Normal string
An error occurred!!

Link : C atan math.h


i)Environmental limits

The number of characters that can be produced by any single conversion shall be at least 4095.


Related links

->C programming vfprintf stdio.h