2016-05-08 29 views
0

創建多個文件,目前我正在學習C,並試圖解決問題。我有它具有以下的文本文件名elements.txt從單一來源文件

elements.txt

Carbon (from Latin: carbo "coal") is a chemical element .. 

Oxygen is a chemical element with symbol O .. 

Platinum is a chemical element with symbol Pt ... 

Silicon is a chemical element with symbol Si ... 

Titanium is a chemical element with symbol Ti ... 

我想創建一個基於元素,如carbon.txtoxygen.txtplatinum.txtsilicon.txttitanium.txt從多個文件elements.txt

這是我的索裏的代碼:

void magic(){ 
    FILE *fp,*fp1, *fp2, *fp3, *fp4, *fp5; 
    char *fn, *fn1, *fn2, *fn3, *fn4, *fn5; 
    int ch; 

    fn1 = "new/carbon.txt"; 
    fn2 = "new/oxygen.txt"; 
    fn3 = "new/platinum.txt"; 
    fn4 = "new/silicon.txt"; 
    fn5 = "new/titanium.txt"; 

    fn = "elements.txt"; 

    // Read file 
    fp = fopen(fn ,"r"); 
    if(fp == NULL){ 
    printf("Error opening %s for reading. Program terminated",fn); 
    } 

    // Write file 
    fp1 = fopen(fn1, "w"); 
    fp2 = fopen(fn2, "w"); 
    fp3 = fopen(fn3, "w"); 
    fp4 = fopen(fn4, "w"); 
    fp5 = fopen(fn5, "w"); 

    if(fp1 == NULL || fp2 == NULL || fp3 == NULL || fp4 == NULL || fp5 == NULL){ 
    printf("Error opening %s for wrting. Program terminated",fn); 
    } 

    while((ch= fgetc(fp)) != '\n') 
    fputc(ch, fp1); 

    while((ch= fgetc(fp)) != '\n') 
    fputc(ch, fp2); 

    while((ch= fgetc(fp)) != '\n') 
    fputc(ch, fp3); 

    while((ch= fgetc(fp)) != '\n') 
    fputc(ch, fp4); 

    while((ch= fgetc(fp)) != EOF) 
    fputc(ch, fp5); 

    printf("All files were created successfuly!.\n"); 
    fclose(fp1); 
    fclose(fp2); 
    fclose(fp3); 
    fclose(fp4); 
    fclose(fp5); 
    fclose(fp); 
} 



    int main(){ 
    magic(); 
    return 0; 
    } 

我得到創造了我的文件,但氧氣被印在鉑和鉑,硅和鈦鈦被打印出來。看起來有一個錯誤,當我正在做一個閱讀角色的while循環時。不知道如何解決這個問題。有沒有辦法使用for-loop來讀取多個文件並寫入多個文件?

任何幫助,將不勝感激!感謝

+2

「計劃終止」該方案是在撒謊... – MikeCAT

+0

處理輸入的空白​​行正常。 – MikeCAT

回答

1

在你.txt輸入文件,爲不同的元素內容通過換行符,而不是一個分離。嘗試重寫它:

Carbon is... 
Oxygen is... 

等(沒有額外的換行符在一段的末尾)。

或者,你可以檢查的2個換行,而不是1的存在,但這將是更加複雜。

(說明:該程序寫入約碳fn1,然後看見一個新行,並切換到fn2然後看見另一個換行符並切換到fn3同樣的事情發生在氧段末尾)。

2

由於意見建議,以使該塊是正確的,你應該添加一個return聲明:

if(fp1 == NULL || fp2 == NULL || fp3 == NULL || fp4 == NULL || fp5 == NULL){ 
    printf("Error opening %s for wrting. Program leaving",fn); 
    return; //add this statement to leave function 
    } 

否則,該語句計劃終止將是一個謊言。

如果你希望你的代碼來處理與只有空格線輸入文件(而不是修改你的輸入文件),把該線路在輸出文件之前添加了只有空格線測試。使用fgets()strstr()strlen()將適用於創建這樣的測試。

+0

更合適的是'exit(1)'或類似的東西,以表示操作系統的非零退出代碼。 – hyst329

+1

@ hyst329 - 'return'允許從調用函數完成其他事情。在這種情況下,'main()'在下一步中退出,但情況並非總是如此。 – ryyker

+0

或將magic()的類型改爲int,然後返回1; 'void'返回類型不是很好的在這裏,因爲它不提供任何資料'主()' – hyst329