gpt4 book ai didi

c - 横向连接

转载 作者:行者123 更新时间:2023-11-30 15:58:40 25 4
gpt4 key购买 nike

嗨,我最近收到了一项 C 语言任务。

该任务的目的是读取两个文本文件,并并排输出每个文件的每一行,并在所述行中间使用分隔符字符串。

示例:

文件 1 包含:

green
blue
red

文件 2 包含:

rain                                
sun

分隔符字符串 = xx

输出=

greenxxrain                                
bluexxsun
redxx

我已经设法做到了这一点,但想知道是否其他人有任何替代方案。这是我的代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int f1, f2;
FILE *file1, *file2;

file1 = fopen("textone", "r"); //open file1 for reading.
file2 = fopen("texttwo", "r"); //open file2 for reading.

//if there are two files ready, proceed.
if (file1 && file2){
do{
//read file1 until end of line or end of file is reached.
while ((f1 = getc(file1)) != '\n' && f1!= EOF ){
//write character.
putchar(f1);
}
//print separator string.
printf("xx");
//read file2 until end of line or end of file is reached.
while ((f2 = getc(file2)) != '\n' && f2!= EOF ){
//write character.
putchar(f2);
}
putchar('\n');
//do this until both files have reached their end.
}while(f1 != EOF || f2 != EOF);
}
}

最佳答案

您可能会发现fgets(3)有用。它可用于一次读取整行。也就是说,它也有缺点 - 例如,您需要知道线路将有多长,或者至少处理线路比缓冲区长的情况。您的实现对我来说似乎很好(除了您应该调用 fclose(3) )。

关于c - 横向连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9611264/

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