fprintf

fprintf

fprintf是C/C++中的一個格式化寫—庫函數;其作用是格式化輸出到一個流/文件中;原型是int fprintf( FILE *stream, const char *format, [ argument ]...),fprintf()函數根據指定的format(格式)發送信息(參數)到由stream(流)指定的文件。

簡介


是C/C++中的一個格式化寫—庫函數;其作用是格式化輸出到一個流/文件中;
函數完整形式: int fprintf(FILE *stream,char *format,[argument])

功能


傳送格式化輸出到一個文件中,
可用於印表機輸出。

用法


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

返回值


若成功則返回輸出字元數,若輸出出錯則返回負值。

程序例


#include
int main(void)
{
FILE *in, *out;
if ((in = fopen("\\AUTOEXEC.BAT", "rt")) == NULL)
{
fprintf(stderr, "Cannot open input file.\n");
return 1;
}
if ((out = fopen("\\AUTOEXEC.BAT", "wt")) == NULL)
{
fprintf(stderr, "Cannot open output file.\n");
return 1;
}
while (!feof(in))
fputc(fgetc(in), out);
fclose(in);
fclose(out);
return 0;
}
舉例用法:
#include
#include
FILE *stream;
void main( void )
{
int i = 10;
double fp = 1.5;
char s[] = "this is a string";
char c = '\n';
stream = fopen( "fprintf.out", "w" );
fprintf( stream, "%s%c", s, c );
fprintf( stream, "%d\n", i );
fprintf( stream, "%f\n", fp );
fclose( stream );
system( "type fprintf.out" );
}
屏幕輸出:
this is a string
10
1.500000
例二
#include
int main()
{
FILE *fp;
int i=617;
char* s = "that is a good new";
fp = fopen("text.dat","w");
fputs("total",fp);
fputs(":",fp);
fprintf(fp,"%d\n",i);
fprintf(fp,"%s",s);
fclose(fp);
return 0;
}
輸出
total:617
that is a good new

規定符


%d, %i 十進位有符號整數
%u 十進位無符號整數
%f 浮點數
%s 字元串
%c 單個字元
%p指針的值
%e, %E 指數形式的浮點數
%x, %X 無符號以十六進位表示的整數
%o 無符號以八進位表示的整數
%g 自動選擇合適的表示法

程序示例


示例一示例二
示例二(輸出)示例三
示例三(輸出)