freopen

freopen

形参说明:
filename:需要重定向到的文件名或文件路径。
mode:代表文件访问权限的字符串。例如,"r"表示“只读访问”、"w"表示“只写访问”、"a"表示“追加写入”。
stream:需要被重定向的文件流。

举例1

#include<stdio.h>
int main()
{
    /* redirect standard output to a file */
    if(freopen("D:\output.txt", "w", stdout) == NULL)
        fprintf(stderr,"error redirecting stdout
");
    /* this output will go to a file */
    printf("This will go into a file.
");
    /*close the standard output stream*/
    fclose(stdout);
    return 0;
}

举例2:即,把输出到屏幕的文本输出到一个文本文件中。

#include<stdio.h>
int main()
{
    int i;
    if (freopen ("D:\output.txt", "w", stdout) == NULL)
        fprintf(stderr, "error redirecting stdout
");
    for (i = 0; i < 10; i++)
        printf("%3d", i);
    printf("
");
    fclose(stdout);
    return 0;
}

举例3:从文件in.txt中读入数据,计算加和输出到out.txt中

#include<stdio.h>
int main()
{
    int a, b;
    freopen("in.txt","r",stdin);
    /* 如果in.txt不在连接后的exe的目录,需要指定路径如D:in.txt */
    freopen("out.txt","w",stdout); /*同上*/
    while (scanf("%d%d", &a, &b) != EOF)
        printf("%d
",a+b);
    fclose(stdin);
    fclose(stdout);
    return 0;
}

 

因上求缘,果上努力~~~~ 作者:每天卷学习,转载请注明原文链接:https://www.cnblogs.com/BlairGrowing/p/13943529.html

原文地址:https://www.cnblogs.com/BlairGrowing/p/13943529.html