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

如何用C语言对不同文件列逐行求和?含多文件扩展方案

Fixing Your C File Summation Code & Adapting to New Requirements

Let's break this down step by step—first fixing your original code that's misbehaving, then adjusting it for the new 50-file scenario.

Part 1: Fixing the Original 8-File Summation Code

Your original code has several critical issues causing runtime errors: uninitialized variables, incorrect file pointer usage, insufficient filename buffer sizes, and missing logic to handle all 1000 lines per file. Here's the corrected version with explanations:

#include <stdio.h>

int main(void) {
    const int NUM_SUM_FILES = 4;    // Corresponding to Filesum1.dat to Filesum4.dat
    const int FILES_PER_GROUP = 2;  // 8 total files = 4 groups × 2 files each
    const int NUM_LINES = 1000;     // Each input file has 1000 lines

    FILE *sum_files[NUM_SUM_FILES];
    char filename[20];  // Larger buffer to avoid overflow from longer filenames

    // Open all output sum files first
    for (int n = 0; n < NUM_SUM_FILES; n++) {
        sprintf(filename, "filesum%d.dat", n + 1);  // Match 1-indexed filename pattern
        sum_files[n] = fopen(filename, "w");
        if (sum_files[n] == NULL) {  // Add error checking for failed file opens
            printf("Error opening output file %s\n", filename);
            return 1;
        }
    }

    // Process each line across all files
    for (int line = 0; line < NUM_LINES; line++) {
        // Initialize sums for the current line to 0
        int sums[NUM_SUM_FILES] = {0};

        // Process each group (e.g., group 0 = all fileX-1.dat files)
        for (int group = 0; group < NUM_SUM_FILES; group++) {
            // Open each file in the current group
            for (int file_idx = 1; file_idx <= FILES_PER_GROUP; file_idx++) {
                sprintf(filename, "file%d-%d.dat", file_idx, group + 1);
                FILE *input_file = fopen(filename, "r");
                if (input_file == NULL) {
                    printf("Error opening input file %s\n", filename);
                    return 1;
                }

                int x0, x1;
                // Skip to the target line (since we process lines sequentially)
                for (int skip = 0; skip < line; skip++) {
                    fscanf(input_file, "%*d %*d");  // Read and discard previous lines
                }
                fscanf(input_file, "%d %d", &x0, &x1);
                sums[group] += x1;  // Sum the second column as per your requirement

                fclose(input_file);
            }
        }

        // Write the sums for this line to each output file
        for (int n = 0; n < NUM_SUM_FILES; n++) {
            fprintf(sum_files[n], "%d\n", sums[n]);
        }
    }

    // Close all output files
    for (int n = 0; n < NUM_SUM_FILES; n++) {
        fclose(sum_files[n]);
    }

    return 0;
}

Key fixes & improvements:

  • Fixed variable initialization: Eliminated uninitialized i that caused random memory access
  • Adequate filename buffers: Avoids buffer overflow from longer filename strings
  • Error checking: Added checks for failed file opens to catch missing files early
  • Line-by-line processing: Properly handles all 1000 lines, summing the second column across corresponding lines in each file group
  • Correct file pointer usage: Uses individual pointers for each input file and writes to the correct output file pointer

Part 2: Adapting to 50 Files (readFile1 to readFile50)

Assuming you want to generate a single sum file where each line is the total of the second column from all 50 files' corresponding lines, here's the modified code:

#include <stdio.h>

int main(void) {
    const int NUM_INPUT_FILES = 50;
    const int NUM_LINES = 1000;

    // Open the single output file
    FILE *sum_file = fopen("totalSum.dat", "w");
    if (sum_file == NULL) {
        printf("Error opening output file totalSum.dat\n");
        return 1;
    }

    // Process each line across all 50 files
    for (int line = 0; line < NUM_LINES; line++) {
        int total_sum = 0;

        for (int file_idx = 1; file_idx <= NUM_INPUT_FILES; file_idx++) {
            char filename[20];
            sprintf(filename, "readFile%d.dat", file_idx);  // Match new filename pattern
            FILE *input_file = fopen(filename, "r");
            if (input_file == NULL) {
                printf("Error opening input file %s\n", filename);
                return 1;
            }

            int x0, x1;
            // Skip to the target line
            for (int skip = 0; skip < line; skip++) {
                fscanf(input_file, "%*d %*d");
            }
            fscanf(input_file, "%d %d", &x0, &x1);
            total_sum += x1;

            fclose(input_file);
        }

        // Write the sum for this line to the output file
        fprintf(sum_file, "%d\n", total_sum);
    }

    fclose(sum_file);
    return 0;
}

If you need to split the 50 files into multiple sum groups (e.g., sum readFile1-readFile10 into one file, etc.), you can adjust the loop structure to mirror the grouping logic from the original fixed code—just define the number of groups and map files to each group accordingly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 06:23:45