gpt4 book ai didi

从单个源文件创建多个文件

转载 作者:太空宇宙 更新时间:2023-11-04 07:01:51 25 4
gpt4 key购买 nike

我目前正在学习 C 并试图解决一个问题。我有一个名为 elements.txt 的文本文件,其中包含以下内容:

元素.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 循环读取多个文件并写入多个文件?

任何帮助将不胜感激!谢谢

最佳答案

正如评论所建议的,为了使这个 block 正确,你应该添加一个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() 将适合创建此类测试。

关于从单个源文件创建多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37100993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com