c - 横向连接

标签 c file-io text-files separator

嗨,我最近收到了一项 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/

相关文章:

python - 使用makedirs创建文件夹时如何覆盖已存在的文件夹?

c++ - 如果在 Intel CPU 上关闭 "SpeedStep Technology",RDTSC() 是否准确?

凯撒密码 (C) : Read from textfile

c++ - 在C/C++中使用stdio文件操作时如何检测磁盘空间不足?

c# - 制表符分隔文本文件中的空列问题

java - 在Java中读取文本文件(.txt)时发生错误

c - 段错误 : 1902 vfscanf. c: 没有这样的文件或目录

android - 将字符串传递给android代码时出现JNI问题

python - Python 中更节省内存的结构表示?

java - 如何确定文件已成功写入?