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

C语言多线程读取文件数组计算和与乘积输出不随文件内容修改变化问题

问题根因

你遇到的输出不变的问题由多个错误共同导致,按影响优先级排序:

  • 文件读取逻辑严重错误:你在read_ints的循环内连续调用了两次fscanf(file, "%d", &i),相当于每读取1个有效元素存入数组,就会跳过后续2个输入值,只有特定位置的输入数值会被存入数组,修改被跳过的数值时程序读取到的数组内容自然不会变化。
  • 硬编码输入文件路径,忽略命令行参数:你运行程序时传入了input.txt参数,但代码中完全没有处理main函数的argc/argv参数,固定读取当前工作目录下的input.txt,如果你修改的是其他路径下的输入文件,程序读的还是旧文件内容。
  • feof接口使用错误:feof会在读取操作触发文件结束后才返回真,你当前的写法会在文件末尾多写入一个无效值到数组,还可能出现数组越界。
  • 缺少异常判断:没有判断fopen是否成功,输入文件不存在/无权限时程序直接读取全零的全局数组内容。
  • 线程函数不符合规范:pthread要求线程回调函数必须返回void*类型,你的两个线程函数缺少return语句,编译会触发警告。

修复后代码

#include <stdio.h>
#include <pthread.h>
#define ARRAY_SIZE 40

int array[ARRAY_SIZE];
int sum = 0;
long long int product = 1;

// 修复后的文件读取函数
void read_ints(const char* file_name)
{
    FILE* file = fopen(file_name, "r");
    // 新增文件打开失败判断
    if (file == NULL) {
        perror("打开输入文件失败");
        return;
    }
    int j = 0;
    // 直接用fscanf返回值判断读取结果,弃用错误的feof用法
    while (j < ARRAY_SIZE && fscanf(file, "%d", &array[j]) == 1) {
        j++;
    }
    // 不足40个元素时补0,避免未定义行为
    while (j < ARRAY_SIZE) {
        array[j++] = 0;
    }
    fclose(file);
}

void* sum_array(void* arg)
{
    for (int i = 0; i < ARRAY_SIZE; i++)
        sum += array[i];
    return NULL; // 新增线程返回值
}

void* product_array(void* arg)
{
    for (int i = 0; i < ARRAY_SIZE; i++)
        product *= array[i];
    return NULL; // 新增线程返回值
}

int main(int argc, char* argv[])
{
    // 读取命令行传入的文件路径
    if (argc < 2) {
        printf("用法: %s <输入文件路径>\n", argv[0]);
        return 1;
    }
    read_ints(argv[1]);
    pthread_t threads[2];
    pthread_create(&threads[0], NULL, sum_array, NULL);
    pthread_create(&threads[1], NULL, product_array, NULL);

    for (int i = 0; i < 2; i++)
        pthread_join(threads[i], NULL);

    printf("sum is: %d \n", sum);
    printf("product is: %lli \n", product);

    return 0;
}

编译运行命令保持不变

gcc yyy.c -o yyy -lpthread
./yyy input.txt

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:15:03