想问一下大家怎么实现两个TXT文件里的内容交错排列然后输入到第三个TXT文件里啊😣😣
举个例子:
1:asd 2:qwe 3:aqswde
asd qw aqswd
#include <stdio.h>
#include <string.h>
int main() {
FILE *file1 = fopen("1.txt", "r");
char a[1000];
fgets(a, sizeof(a), file1);
fclose(file1);
FILE *file2 = fopen("2.txt", "r");
char b[1000];
fgets(b, sizeof(b), file2);
fclose(file2);
FILE *file3 = fopen("3.txt", "w");
char c[2000];
for (int i = 0; i <= len(a) ; i++)
{
c[i * 2] = a[i];
}
for (int i = 0; i <= len(b); i++)
{
c[i * 2 + 1] = b[i];
}
fputs(c, file3);
fclose(file3);
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void){
char str1[2000];
char str2[2000];
char str3[4000];
FILE * fp1 = fopen("TXT1.txt","r");
if(fp1==NULL){
printf("文件打开失败!\n");
return -1;
}
FILE * fp2 = fopen("TXT2.txt","r");
if(fp2==NULL){
printf("文件打开失败!\n");
return -1;
}
int i=0;
char ch;
while(feof(fp1)==0&&i<2000){ //读取第一个文件的每一个字符
int num=fscanf(fp1,"%c",&ch);
if(feof(fp1)==0&&num!=0){
str1[i]=ch;
i++;
}
}
if(str1[i-1]!='\n'){
str1[i]='\n';
i++;
}
str1[i]='\0';
// for(int z=0;z<i;z++){
// printf("str1[%d]=%c,%d\n",z,str1[z],str1[z]);
// }
// printf("str1=%s\n",str1);
fclose(fp1);
int j=0;
while(feof(fp2)==0&&j<2000){ // 读取第二个文件的每一个字符
// https://www.runoob.com/cprogramming/c-function-fscanf.html
int num=fscanf(fp2,"%c",&ch);
if(feof(fp2)==0&&num!=0){
str2[j]=ch;
j++;
}
}
if(str2[j-1]!='\n'){
str2[j]='\n';
j++;
}
str2[j]='\0';
// for(int z=0;z<j;z++){
// printf("str2[%d]=%c,%d\n",z,str2[z],str2[z]);
// }
// printf("str2=%s\n",str2);
fclose(fp2);
int k=0;
int len=0;
while(k<i||k<j){ // 将两个文件的字符交错存入第三个数组
if(k<i){
str3[len]=str1[k];
len++;
}
if(k<j){
str3[len]=str2[k];
len++;
}
k++;
}
str3[len]='\0';
// for(int z=0;z<len;z++){
// printf("str3[%d]=%c,%d\n",z,str3[z],str3[z]);
// }
// printf("str3=%s\n",str3);
fclose(fp2);
FILE * fp3 = fopen("TXT3.txt","w");
if(fp3==NULL){
printf("文件打开失败!\n");
return -1;
}
k=0;
int warpNum=0;
while(k<len){ // 将已经交错排列的字符串写入第三个文件
char ch = str3[k];
if(ch=='\n'){
warpNum++;
if(warpNum%2==0&&warpNum!=0){
fprintf(fp3,"%c",ch);
}
}else{
fprintf(fp3,"%c",ch);
}
k++;
}
fclose(fp3);
return 0;
}
c1=fgetc(f1);
c2=fgetc(f2);
fputc(c1,f3);
fputc(c2,f3);