fprintf

fprintf

格式化庫函數
fprintf是C/C++中的一個格式化寫—庫函數;其作用是格式化輸出到一個流/文件中;原型是int fprintf( FILE *stream, const char *format, [ argument ]...),fprintf()函數根據指定的format(格式)發送信息(參數)到由stream(流)指定的文件。
    中文名:fprintf 外文名: 定義: 功能:傳送格式化輸出到一個文件中 成功返回值:輸出字符數 錯誤返回值:返回負值

簡介

是C/C++中的一個格式化寫—庫函數;其作用是格式化輸出到一個流/文件中;

函數完整形式: int fprintf(FILE *stream,char *format,[argument])

功能

傳送格式化輸出到一個文件中,

可用于打印機輸出。

用法

#include

#include

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

fprintf()函數根據指定的format(格式)發送信息(參數)到由stream(流)指定的文件. fprintf()隻能和printf()一樣工作. fprintf()的返回值是輸出的字符數,發生錯誤時返回一個負值.

返回值

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

程序例

/* Program to create backup of the

AUTOEXEC.BAT file */

#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, "%dn", i );

fprintf( stream, "%fn", 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,"%dn",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 自動選擇合适的表示法

相關詞條

相關搜索

其它詞條