2011-03-11 67 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; 
} 
相關問題