淡然者

fprintf

fprintf编辑

fprintf是C/C++中的一个格式化写—库函数;其作用是格式化输出到一个流/文件中;原型是int fprintf( FILE *stream, const char *format, [ argument ]...),fprintf()函数根据指定的format(格式)发送信息(参数)到由stream(流)指定的文件。
中文名
fprintf
功 能
传送格式化输出到一个文件中
成功返回值 
输出字符数
错误返回值
返回负值

1定义编辑

int fprintf (FILE* stream, const char*format, [argument])
其中,FILE*stream为文件指针,const char* format以什么样的格式输出,[argument]为输入列表
" src="/CuteSoft_Client/CuteEditor/Images/anchor.gif">

2功 能编辑

传送格式化输出到一个文件中,
可用于打印机输出。
" src="/CuteSoft_Client/CuteEditor/Images/anchor.gif">

3用 法编辑

#include <stdio.h>
#include<stdlib.h>
int fprintf( FILE *stream, const char *format, ... );
fprintf()函数根据指定的format(格式)发送信息(参数)到由stream(流)指定的文件. fprintf()只能和printf()一样工作. fprintf()的返回值是输出的字符数,发生错误时返回一个负值.

4规定符编辑

%d 十进制有符号整数
%u 十进制无符号整数
%f 浮点数
%s 字符串
%c 单个字符
%p指针的值
%e 指数形式的浮点数
%x, %X 无符号以十六进制表示的整数
%0 无符号以八进制表示的整数
%g 自动选择合适的表示法[1] 

5程序示例编辑

示例一[1] 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*ProgramtocreatebackupoftheAUTOEXEC.BATfile*/
#include <stdio.h>
int main(void)
{
    FILE *in,*out;
    in = fopen("\\AUTOEXEC.BAT""rt");
    if(in == NULL)
    {
        fprintf(stderr, "Can not open inputfile.\n");
        return 1;
    }
    out = fopen("\\AUTOEXEC.BAT""wt");
    if(out == NULL)
    {
        fprintf(stderr, "Can not open outputfile.\n");
        return 1;
    }
    while(!feof(in))
        fputc(fgetc(in), out);
    fclose(in);
    fclose(out);
    return 0;
}
示例二[1] 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
FILE* stream;
int 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("typefprintf.out");
    return 0;
}
屏幕输出:
1
2
3
this is a string
10
1.500000
示例三
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
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;
}
输出
1
2
total:617
that is a good new

posted on 2015-05-26 07:59  wesun  阅读(637)  评论(0编辑  收藏  举报