如何从文件读取输入并将输出写入C中的另一个文件

我不太擅长C.如何让我的程序从文件中读取输入并将输出写入C中的另一个文件?

对于C ++, 这里和这里都有很好的例子。

对于C,请检查此参考 。 它打开一个文件,在其上写入内容,然后从中读取。 这几乎就是你要找的东西。 此外, 这个页面很棒,因为它详细解释了fopen / fread / fwrite。

只需阅读c文件输入/输出上的维基百科条目 。

使用karlphillip的链接我得到了这个代码:)

编辑:改进的代码版本。

 #include  #include  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); } 

如果您只有一个输入文件而只有一个输出文件,最简单的方法是使用freopen:

 #include  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; }