fprintf详解及用法

本文详细介绍了C++标准库函数fprintf的用法,包括向文件中直接写入、读取以及控制输出到屏幕的区别,展示了如何在不同环境中进行格式化输出。
摘要由CSDN通过智能技术生成

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是无缓冲的,会直接输出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值