我的原始代码用于读取和复制一个文件到另一个文件(内容包含几个段落,每个段落用换行符分隔)。但现在我需要读取文件并将其写入几个不同的文件(每个文件只包含一个段落)。但我不知道该怎么做,希望任何人都可以帮忙。 原始代码如下所示
#include <stdio.h>
#include <stdlib.h>
int main(void) {
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
char ch, file_name[10];
FILE *fp;
FILE *fa;
printf("enter the name of file\n");
gets(file_name);
fa=fopen("write.txt","w");
fp=fopen(file_name,"r");
if(fp==NULL)
{
perror("error while opening the file. \n");
exit(1);
}
printf("the contents of %s file are :\n", file_name);
while((ch=fgetc(fp))!=EOF){
printf("%c",ch);
fprintf(fa,"%c",ch);
}
fclose(fa);
fclose(fp);
return 0;
}
答案 0 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
int main(void) {
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
char ch, file_name[10];
FILE *fp;
FILE *fa;
FILE *fc;
FILE *fd;
FILE *fe;
FILE *ff;
printf("enter the name of file\n");
gets(file_name);
fa=fopen("write0.txt","w");
fp=fopen(file_name,"r");
fc=fopen("write1.txt","w");
fd=fopen("write2.txt","w");
fe=fopen("write3.txt","w");
ff=fopen("write4.txt","w");
if(fp==NULL)
{
perror("error while opening the file. \n");
exit(1);
}
printf("the contents of %s file are :\n", file_name);
while((ch=fgetc(fp))!=EOF){
printf("%c",ch);
fprintf(fa,"%c",ch);
if(ch=='\n'){
if((ch=fgetc(fp))=='\n'){
goto a;
}
}
}
a:
while((ch=fgetc(fp))!=EOF){
printf("%c",ch);
fprintf(fc,"%c",ch);
if(ch=='\n'){
if((ch=fgetc(fp))=='\n'){
goto b;
}
}
}
b:
while((ch=fgetc(fp))!=EOF){
printf("%c",ch);
fprintf(fd,"%c",ch);
if(ch=='\n'){
if((ch=fgetc(fp))=='\n'){
goto c;
}
}
}
c:
while((ch=fgetc(fp))!=EOF){
printf("%c",ch);
fprintf(fe,"%c",ch);
if(ch=='\n'){
if((ch=fgetc(fp))=='\n'){
goto d;
}
}
}
d:
while((ch=fgetc(fp))!=EOF){
printf("%c",ch);
fprintf(ff,"%c",ch);
}
fclose(fa);
fclose(fp);
fclose(fc);
fclose(fd);
fclose(fe);
fclose(ff);
return 0;
}