C programming vfprintf stdio.h


int vfprintf(FILE * restrict stream ,
  const char * restrict format ,
  va_list arg);

Parameters :
stream -A stream to which the data is to be outputted.

format -The string with the conversion specifier.

arg -A lists of variables.

Return type
int-Returns the number of characters transmitted,or a negative value if an output or encoding error occurred.

In C programming the <stdio.h> vfprintf function is equivalent to fprintf function but instead of using ellipsis as the third argument it is replaced by va_list.A code example is given below.

Link : C fprintf stdio.h

Note include the header <stdarg.h> to use va_list , va_start macro.
Code example

void func(char* format , …)
{
FILE *fp=fopen(“text.txt” , “w+”);

va_list arg ;

va_start(arg , format);

vfprintf(fp , format , arg);

va_end( arg );

fclose( fp );
}

int main( )
{
func( “New number %d” , 890);

getchar( );
return 0 ;
}

Run the program and open the file “text.txt” you will see the string “New number 890”.





All the conversion specifier rules still apply

Note since ‘vfprintf’ is equivalent to ‘fprintf’ all the conversion specifier rules still applies.An exhaustive code example is given below.

Code example

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

void error(char * format , … )
{
va_list arg ;

va_start(arg , format);

vfprintf(stderr , format , arg);

va_end( arg );
}

int main( )
{
FILE *fp=fopen(“Text.txt” , “r”);

if(fp==NULL)
{
error(“Error:%s” , “file opening failed” );
}
else
  /* read the file or do anything */

fclose(fp);

getchar( );
return 0;
}

If the file “Text.txt” does not exist you will get the output “Error:file opening failed”.


Related links

->C fclose stdio.h

->C programming vprintf stdio.h