Scanf从文件中读入,printf写入到文件 - 谙忆-人生之旅

谙忆-人生之旅

学不止步,梦不停歇-陈浩翔

Scanf从文件中读入,printf写入到文件

 2015年09月10日

重定向方式读写文件和非重定向方式读写文件


重定向方式读写文件

重定向方式读写文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#define LOCAL
int main()
{
    #ifdef LOCAL
    freopen("input.txt","r",stdin);
    //使得scanf从文件input.txt读入
    //r只读,如果文件不存在,出错
    freopen("output.txt","w",stdout);
    //使得printf写入文件output.txt
    //w只写,如果文件不存在,建立新文件
    #endif
    //只有定义了符号LOCAL,才编译2条freopen语句。
    int j;
    scanf("%d",&j);
    for(int i=0;i<5;i++)
        printf("%d\n",i);
    printf("%d\n",j);
    return 0;
}

非重定向方式读写文件

非重定向方式读写文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
    FILE *fin,*fout;
    fin=fopen("data.in.txt","r");
    fout=fopen("data.out.txt","w");
    int j;
    fscanf(fin,"%d",&j);
    for(int i=0;i<5;i++)
        fprintf(fout,"%d\n",i);
    fprintf(fout,"%d\n",j);
    fclose(fin);
    fclose(fout);
    return 0;
}

本文章由[谙忆]编写, 所有权利保留。 欢迎转载,分享是进步的源泉。

转载请注明出处:http://chenhaoxiang.cn

本文源自人生之旅_谙忆的博客