You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言逐行交替合并两个文本文件无输出问题求助

代码问题排查

核心问题(导致目标文件无内容的主要原因)

  • ch1、ch2未初始化:两个变量定义后没有赋值就直接在while循环里判断if(ch1!=EOF),初始值为内存随机垃圾值,若随机值刚好等于EOF,会直接跳过所有文件读取写入逻辑,导致目标文件为空。
  • 未手动关闭文件指针:程序结束前没有调用fclose()刷入内存缓存,若程序停在getch()等待用户输入阶段,写入内容还未同步到磁盘,查看目标文件会显示为空。
  • fgetc返回值类型不匹配:fgetc返回值为int类型(EOF是值为-1的int常量),用char类型存储返回值时,若编译环境中char为无符号类型,永远无法匹配到EOF,会导致死循环或读取逻辑异常。

其他功能缺陷

  • 未写入换行符:读取到行尾\n后直接跳出内层循环,没有将\n写入目标文件,合并后所有行内容会连在一起,不符合逐行合并的要求。
  • 缺少<conio.h>头文件:代码最后调用的getch()属于conio库,未引入对应头文件会导致部分编译环境编译失败。
  • 边界逻辑漏洞:若其中一个文件提前读完,剩余另一个文件的最后一行会被丢弃。

修正后代码

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

int main()
{
    FILE *pointer1, *pointer2, *pointer3;
    char source1[80],source2[80],target[80];
    // 改为int类型存储fgetc返回值,同时初始化避免随机值
    int ch1 = 0, ch2 = 0;

    printf("Enter the source and source 2\n");
    scanf("%s %s", source1,source2);

    printf("Enter the destination\n");
    scanf("%s",target);

    pointer1 = fopen(source1,"r");
    pointer2 = fopen(source2,"r");
    pointer3 = fopen(target,"w");

    if(pointer1 == NULL || pointer2==NULL || pointer3==NULL)
    {
        printf("Cannot open a file\n ");
        exit(1);
    }
    
    while(1)
    {
        if(ch1 != EOF)
        {
            ch1 = fgetc(pointer1);
            while(ch1 != '\n' && ch1 != EOF)
            {
                fputc(ch1, pointer3);
                ch1 = fgetc(pointer1);
            }
            // 写入行尾换行符
            if(ch1 == '\n')
                fputc('\n', pointer3);
        }
        if(ch2 != EOF)
        {
            ch2 = fgetc(pointer2);
            while(ch2 != '\n' && ch2 != EOF)
            {
                fputc(ch2, pointer3);
                ch2 = fgetc(pointer2);
            }
            // 写入行尾换行符
            if(ch2 == '\n')
                fputc('\n', pointer3);
        }

        if(ch1 == EOF && ch2 == EOF)
            break;
    }
    // 关闭文件刷入缓存
    fclose(pointer1);
    fclose(pointer2);
    fclose(pointer3);

    printf("Merging completed successfully\n");
    printf("Press any key to exit\n");
    getch();
    return 0;
}

内容的提问来源于stack exchange,提问作者Ashish Bajpai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 23:27:03