fprintf是C/C++中的一个格式化库函数,可以格式化输出到一个流文件中,使得信息输出到指定的文件;通过文件流指针来控制;调用fprintf函数时需包含头文件stdio.h。
fprint的原型函数为:int fprintf( FILE *stream, const char *format, ... )
fprintf的调用格式为:fprintf(指定文件, 数据流,参量表)
指定文件:通过文件流指针来控制。
数据流:格式化字符串等各种信息。
参量表:需要输出的一系列参数。
1.将内容直接写入文件中
例如:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* fp;
fp = fopen("d:\\pp.txt","w+");
fprintf(fp,"%d,%x,%o",20,20,20);
return 0;
}
2.将内容写到指定文件中并打印输出到屏幕
例如:
#include <cstdio>
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
char ch[100];
if((fp=fopen("add.txt","r+"))==NULL){
printf("Cannot open the file...");
exit(1);
}
for(int i=0;i<10;i++){
fprintf(fp,"The count number is %d\n",i+1);
}
fclose(fp);
if((f=fopen("add.txt","r+"))==NULL){
printf("Cannot open the file...");
exit(1);
}
printf("File content is--\n");
printf("\n...............print the strings..............\n\n");
while(!feof(fp)){
fgets(ch,100,fp);
printf("%s",ch);
}
fclose(fp);
return 0;
}
编译后运行输出:
The count number is 1
The count number is 2
The count number is 3
The count number is 4
The count number is 5
The count number is 6
The count number is 7
The count number is 8
The count number is 9
The count number is 10
3.将内容直接输出到屏幕
例如:
#include<stdio.h>
int main()
{
fprintf(stdout,"World!");
fprintf(stderr,"Hello");
return0;
}
编译后运行输出:
HelloWorld!
在默认情况下,stdout是行缓冲的,输出会放在一个buffer里面,只有到换行的时候,才会输出到屏幕;而stderr是无缓冲的,会直接输出。