創建多個文件,目前我正在學習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.txt
,oxygen.txt
,platinum.txt
,silicon.txt
和titanium.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來讀取多個文件並寫入多個文件?
任何幫助,將不勝感激!感謝
「計劃終止」該方案是在撒謊... – MikeCAT
處理輸入的空白行正常。 – MikeCAT