【问题标题】:Sideways conCATenate横向连接
【发布时间】: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);
    }
}

【问题讨论】:

标签: c file-io text-files separator


【解决方案1】:

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

【讨论】:

  • 在主循环之后使用 fclose() 是否正确?
  • 文本文件也可以是可变长度的,我尝试使用 fgets() 但想不出将行与分隔符合并在一起的方法
  • fclose 的问题是肯定的,你不需要 fgets,你的实现是可以的。
【解决方案2】:

您可以编写一个简单的函数来避免do { ... } while 循环中的“大”重复:

static void read_and_echo_line(FILE *fp)
{
    int c;
    while ((c = getc(fp)) != EOF && c != '\n')
        putchar(c);
}


...

    do
    {
        read_and_echo_line(file1);
        printf("xx");   
        read_and_echo_line(file2);
        putchar('\n');    
    } while (!feof(file1) || !feof(file2));

在这种情况下,如图所示使用feof() 是相当合理的(尽管它不是大多数时候使用的函数)。或者:

static int read_and_echo_line(FILE *fp)
{
    int c;
    while ((c = getc(fp)) != EOF && c != '\n')
        putchar(c);
    return(c);
}

...

    do
    {
        f1 = read_and_echo_line(file1);
        printf("xx");   
        f2 = read_and_echo_line(file2);
        putchar('\n');    
    } while (f1 != EOF || f2 != EOF);

【讨论】:

    猜你喜欢
    • 2016-06-21
    • 1970-01-01
    • 2019-07-18
    • 2021-02-21
    • 2020-05-16
    • 1970-01-01
    • 2020-05-07
    • 2019-02-05
    • 2022-01-23
    相关资源
    最近更新 更多