C语言屏幕输出的内容如何保存到文件中

C语言屏幕输出的内容如何保存到文件中

C语言中用流替换函数freopen可以从文件中读取数据或将数据输出到文件中。

需要引用库"stdio.h",即

#include<stdio.h>

freopen的声明如下:

FILE *freopen(const char * restrict filename, const char * restrict mode, FILE * restrict stream);

形参说明:

filename:需要重定向到的文件名或文件路径。

mode:代表文件访问权限的字符串。例如,"r"表示“只读访问”、"w"表示“只写访问”、"a"表示“追加写入”。

stream:需要被重定向的文件流。

返回值:如果成功,则返回该指向该输出流的文件指针,否则返回为NULL。

用法:

将输入流从stdin替换成指定文件可以从文件中读取数据;

将输出流从stdout替换成指定文件可以将数据输出到文件中。

下面举个例子:

#include<stdio.h>

int main(){
    freopen("in.txt","r",stdin); //从in.txt中读数据
    freopen("out.txt","w",stdout);//向out.txt中写数据
    int a,b;
    while(~scanf("%d%d", &a, &b)){
        printf("%d %d\n");
    }
    return 0;
}

温馨提示:答案为网友推荐,仅供参考
相似回答