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

读取两个纯数字文件并合并排序时触发runtime error,求问题定位

问题排查:读取两文件数字合并排序的运行时错误

需实现读取两个仅含数字的文件,合并所有数字后排序的功能,但多次尝试均出现runtime error,以下是代码、输入示例及期望输出:

原代码

#include<stdio.h>
#include<stdlib.h>
#define N 128

int main(){
    int i, j, temp, count=0;
    int data1[N];
    char fname1[N], fname2[N];
    
    scanf("%s", fname1);
    FILE *f1 = fopen(fname1, "r");
    
    while(1){
        fscanf(f1, "%d", &data1[i]);
        i++;
        if(feof(f1)){
            break;
        }
        count++;
    }
    
    fclose(f1);
    
    scanf("%s", fname2);
    FILE *f2 = fopen(fname2, "r");
    
    while(1){
        fscanf(f2, "%d", &data1[i]);
        i++;
        if(feof(f2)){
            break;
        }
        count++;
    }
    
    fclose(f2);
    
    for(j=count; j>1; j--){
        for(i=0; i<j-1; i++){
            if(data1[i]>data1[i+1]){
                temp = data1[i];
                data1[i] = data1[i+1];
                data1[i+1] = temp;
            }
        }
    }
    
    for(i=0; i<count; i++){
        printf("%d ", data1[i]);
    }
    
    return 0;
}

输入示例

文件1内容:

2 5 9 10 15 18 18 20 30 58 

文件2内容:

1 3 10 12 19 22 25 28 40 

期望输出

1 2 3 5 9 10 10 12 15 18 18 19 20 22 25 28 30 40 58 

错误原因及修复方案

  • 变量i未初始化:int i定义后未赋值,初始值为随机垃圾值,第一次循环就会越界访问data1数组,直接触发运行时错误。修复:在使用前将i初始化为0。
  • feof使用逻辑错误:feof仅在读取操作失败后才会置位,当前逻辑会导致最后一次读取失败后,仍执行i++并将无效值存入数组,同时count多统计一次。修复:通过fscanf的返回值判断是否读取成功(成功返回1,失败返回EOF或0)。
  • 未检查文件打开状态:如果输入的文件名不存在/无权限,fopen会返回NULL,后续操作空指针会直接崩溃。修复:每次fopen后检查指针是否为NULL,处理打开失败的情况。
  • 数组越界风险:若两文件数字总数超过128,data1数组会越界。修复:读取时检查i是否小于N,避免越界;或改用动态内存分配。

修正后的代码

#include<stdio.h>
#include<stdlib.h>
#define N 128

int main(){
    int i = 0, j, temp, count=0;
    int data1[N];
    char fname1[N], fname2[N];
    
    scanf("%s", fname1);
    FILE *f1 = fopen(fname1, "r");
    if(f1 == NULL){
        printf("Failed to open file %s\n", fname1);
        return 1;
    }
    
    // 读取第一个文件的数字
    while(i < N && fscanf(f1, "%d", &data1[i]) == 1){
        count++;
        i++;
    }
    fclose(f1);
    
    scanf("%s", fname2);
    FILE *f2 = fopen(fname2, "r");
    if(f2 == NULL){
        printf("Failed to open file %s\n", fname2);
        return 1;
    }
    
    // 读取第二个文件的数字
    while(i < N && fscanf(f2, "%d", &data1[i]) == 1){
        count++;
        i++;
    }
    fclose(f2);
    
    // 冒泡排序
    for(j=count; j>1; j--){
        for(i=0; i<j-1; i++){
            if(data1[i]>data1[i+1]){
                temp = data1[i];
                data1[i] = data1[i+1];
                data1[i+1] = temp;
            }
        }
    }
    
    // 输出结果
    for(i=0; i<count; i++){
        printf("%d ", data1[i]);
    }
    printf("\n");
    
    return 0;
}

内容的提问来源于stack exchange,提问作者せいが

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:35:29