C fprintf function writes data to a file
Syntax
C fprintf function has the following format.
int fprintf(FILE *stream, const char *format, ...);
Header
C fprintf function is from header file stdio.h
.
Description
C fprintf function outputs the values to the stream and returns the number of characters actually printed on success or a negative number on failure.
The format control string are identical to those in printf();
Example
Output data to a file using C fprintf function
#include <stdio.h>
#include <stdlib.h>
// w w w .j av a2 s .c o m
int main(void)
{
FILE *fp;
if((fp=fopen("test", "wb"))==NULL) {
printf("Cannot open file.\n");
exit(1);
}
fprintf(fp, "this is a test %d %f", 10, 20.01);
fclose(fp);
return 0;
}
Example 2
#include <stdio.h>
#include <io.h>
#include <stdlib.h>
/* w ww. j a va 2 s . com*/
int main(void)
{
FILE *fp;
char s[80];
int t;
if((fp=fopen("test", "w")) == NULL) {
printf("Cannot open file.\n");
exit(1);
}
printf("Enter a string and a number: ");
fscanf(stdin, "%s%d", s, &t); /* read from keyboard */
fprintf(fp, "%s %d", s, t); /* write to file */
fclose(fp);
if((fp=fopen("test","r")) == NULL) {
printf("Cannot open file.\n");
exit(1);
}
fscanf(fp, "%s%d", s, &t); /* read from file */
fprintf(stdout, "%s %d", s, t); /* print on screen */
return 0;
}