2011-03-11 68 views
4

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

+1

你的问题和标签说'C',但你的标题说'C++' 。这是什么? – Oded

+1

http://www.cplusplus.com/reference/clibrary/cstdio/ – Muggen

+0

你有什么试过?什么不工作?堆栈溢出不是一个机械土耳其人;) –

回答

4

对于C++,有很多示例herehere。对于C,检查this reference。它打开一个文件,在它上面写下一些内容,然后从中读取。这几乎是你在找什么。 另外,this page is great,因为它详细解释fopen/fread/fwrite。

+0

谢谢,但我需要在C中的答案不在C + + – duaa

+0

好吧,你的原那么问题就不对了。我会在短短一秒内更新。 – karlphillip

+0

非常感谢你 – duaa

0

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

编辑:的代码的改进版。

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

我编辑了代码,纠正了一些严重的问题。 –

0

如果只有一个输入文件,只有一个输出文件,最简单的方法是使用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; 
} 
相关问题