Tuesday, July 28, 2009

What is the work & use of fprintf() function in C or C++language?

I need the work of "fprintf()" function

What is the work %26amp; use of fprintf() function in C or C++language?
In layman's terms, it allows you to take characters from a STREAM and format them.





The difference between printf and fprintf is that printf takes data from variables formats that data, and outputs it to the standard output, whereas fprintf takes its data from a stream (e.g. a file) and formats the data before sending it to output.





So, if you want to format numbers and strings that you are working with in the form of variables, use printf.





Example:





int x=1;


printf("%d",x);





If you are working with data from the FILE, use fprintf:





Example:





int main ()


{


FILE * pFile;


int n;


char name [100];





pFile = fopen ("myfile.txt","w");


for (n=0 ; n%26lt;3 ; n++)


{


puts ("please, enter a name: ");


gets (name);


fprintf (pFile, "Name %d [%-10.10s]\n",n,name);


}


fclose (pFile);





return 0;


}





Hope that helps.





P.S. watch out for sprintf!
Reply://in C++


#include %26lt;fstream%26gt;


#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


using namespace std;





int main()


{


char name[20];


cout %26lt;%26lt; "your name ";


cin.getline(name, 40,'\n');


return 0;


}
Reply:http://www.cplusplus.com/reference/clibr...
Reply:The fprintf() function sends information (the arguments) according to the specified format to the file indicated by stream. fprintf() works just like printf () as far as the format goes. The return value of fprintf() is the number of characters outputted, or a negative number if an error occurs.


An example:


char name[20] = "Mary";


FILE *out;


out = fopen( "output.txt", "w" );


if( out != NULL )


fprintf( out, "Hello %s\n", name );
Reply:Syntax:


#include %26lt;stdio.h%26gt;


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











The fprintf() function sends information (the arguments) according to the specified format to the file indicated by stream. fprintf() works just like printf() as far as the format goes. The return value of fprintf() is the number of characters outputted, or a negative number if an error occurs. An example:





char name[20] = "Mary"; FILE *out; out = fopen( "output.txt", "w" ); if( out != NULL ) fprintf( out, "Hello %s\n", name );


No comments:

Post a Comment