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;
}
精彩评论