开发者

How to read inputs from a file and to write outputs to another file in C

开发者 https://www.devze.com 2023-02-16 19:59 出处:网络
I not very good at C. How can I make my program read inputs from a file and to write outputs to a开发者_如何学JAVAnother file

I not very good at C. How can I make my program read inputs from a file and to write outputs to a开发者_如何学JAVAnother file in C?


Using karlphillip's link I got this code :)

EDIT : Improved version of code.

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    FILE *fs, *ft;
    int ch;
    fs = fopen("pr1.txt", "r");
    if ( fs == NULL )
    {
        fputs("Cannot open source file\n", stderr);
        exit(EXIT_FAILURE);
    }
    ft = fopen("pr2.txt", "w");
    if ( ft == NULL )
    {
        fputs("Cannot open target file\n", stderr);
        fclose(fs);
        exit(EXIT_FAILURE);
    }
    while ((ch = fgetc(fs)) != EOF)
    {
        fputc(ch, ft);
    }
    fclose(fs);
    fclose(ft);
    exit(EXIT_SUCCESS);
}


If you have only one input file and only one output file, the simplest way is to use freopen:

#include <cstdio>
int main ()
{
    freopen("input.txt","r",stdin);
    freopen("output.txt", "w", stdout);

    /* Now you can use cin/cout/scanf/printf as usual,
    and they will read from the files specified above
    instead of standard input/output */
    int a, b;
    scanf("%d%d", &a, &b);
    printf("%d\n", a + b);

    return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消