一个文件A中内容以行存储,如果命名为a1,a2,a3....行,另一个文件B中为b1,b2,b3,b4,b5....。A和B文件内容不一定等长,使用c、shell分别实现内容合并,形式为a1b1a2b2a3b3a4b4b5....。
解析
程序环境为Linux环境下gcc编译。
void file()
{
FILE *fp1, *fp2, *fp3;
char str1[1024];
char str2[1024];
if ((fp1 = fopen("a.txt", "r")) == NULL)
{
printf("open fp1 fail\n");
exit(0);
}
if ((fp2 = fopen("b.txt", "r")) = NULL)
{
printf("open fp2 fail\n");
exit(1);
}
if ((fp2 = fopen("c.txt", "wb+")) == NULL)
{
printf("open fp3 fail\n");
exit(2);
}
while (fgets(str1, 1024, fp1) && fgets(str2, 1024, fp2))
{
fputs(str1, fp3);
fputs(str2, fp3);
}
while (fgets(str1, 1024, fp1))
{
fputs(str1, fp3);
}
while (fgets(str2, 1024, fp2))
{
fputs(str2, fp3);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
}
-------shell--------------------------------------
paste -d "\n" a.txt b.txt > c.txt
sed /^$/d c.txt
解析
程序环境为Linux环境下gcc编译。
void file()
{
FILE *fp1, *fp2, *fp3;
char str1[1024];
char str2[1024];
if ((fp1 = fopen("a.txt", "r")) == NULL)
{
printf("open fp1 fail\n");
exit(0);
}
if ((fp2 = fopen("b.txt", "r")) = NULL)
{
printf("open fp2 fail\n");
exit(1);
}
if ((fp2 = fopen("c.txt", "wb+")) == NULL)
{
printf("open fp3 fail\n");
exit(2);
}
while (fgets(str1, 1024, fp1) && fgets(str2, 1024, fp2))
{
fputs(str1, fp3);
fputs(str2, fp3);
}
while (fgets(str1, 1024, fp1))
{
fputs(str1, fp3);
}
while (fgets(str2, 1024, fp2))
{
fputs(str2, fp3);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
}
-------shell--------------------------------------
paste -d "\n" a.txt b.txt > c.txt
sed /^$/d c.txt