【发布时间】:2012-03-08 00:27:18
【问题描述】:
嗨,我最近接到了 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);
}
}
【问题讨论】:
-
精确副本:stackoverflow.com/questions/9555167/…(为此我创建了一个漂亮的状态机 ;-)
-
查找
paste命令。
标签: c file-io text-files separator