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

无法打开文件求助:C语言读取文件计算温度平均值程序报错

Troubleshooting Your C Program: File Opening & Calculation Issues

Hey there! Let's break down why your program is throwing the "Failed to open file" error, plus fix some hidden issues that would mess up your temperature average calculation.

First: Fixing the "Failed to open file" Error

The most common reasons for this error are tied to file location, naming, or permissions:

  • Check the file path: You’re using a relative path ("Input_file.txt"), which means the file must be in the same folder as your program’s executable. If it’s stored elsewhere, use an absolute path (e.g., C:\\Documents\\Input_file.txt on Windows — note the double backslashes to escape the character, or /home/yourname/Input_file.txt on Linux/macOS).
  • Verify filename spelling & case: Operating systems like Linux and macOS are case-sensitive. If your actual file is named input_file.txt (lowercase "i"), the program won’t recognize Input_file.txt (uppercase "I"). Double-check the exact filename.
  • Check file permissions: On Linux/macOS, make sure your program has permission to read the file. Run chmod +r Input_file.txt in the terminal to grant read access.

Second: Fixing Hidden Bugs in Your Code

Even if you get the file to open, your current code has issues that will give incorrect results:

  1. Wrong format specifier in fscanf: You used %.2f to read the temperature, but fscanf doesn’t accept precision specifiers for floats. Use %f instead — %.2f is only for output functions like printf/fprintf.
  2. Incorrect average calculation: You’re dividing sumTemp by 4 every loop iteration, which updates the average after each row instead of computing it once all data is read. You should track the number of data points and calculate the average after the loop finishes.
  3. Hardcoded data count: Using 4 as the divisor assumes you always have 4 data points. If your input file has more or fewer rows, this will be wrong.

Corrected Code

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

int main(void){
    FILE *myfile, *output_file;
    int month, day, timeHour, timeMinute, stnNumber;
    float temperature;
    float sumTemp = 0.0;
    float averageTemp = 0.0;
    int count = 0; // Track number of valid temperature readings

    // Open input file
    myfile = fopen("Input_file.txt", "r");
    if(myfile == NULL){
        printf("Failed to open file\n");
        exit(1);
    }

    // Open output file
    output_file = fopen("average_sum.txt", "w");
    if(output_file == NULL) {
        printf("The output file was not opened.\n");
        fclose(myfile); // Close input file before exiting to avoid leaks
        exit(1);
    }

    // Read data correctly: use %f instead of %.2f, check for 6 matched values
    while(fscanf(myfile, "%d %d %d %d %d %f", &month, &day, &timeHour, &timeMinute, &stnNumber, &temperature) == 6){
        sumTemp += temperature;
        count++; // Increment count for each valid reading
    }

    // Calculate average only if we have valid data
    if(count > 0){
        averageTemp = sumTemp / count;
        fprintf(output_file, "Average Temperature: %.2f\n", averageTemp);
        printf("Success! Average temperature written to average_sum.txt\n");
    } else {
        fprintf(output_file, "No valid temperature data found.\n");
        printf("No valid data was read from the input file.\n");
    }

    // Clean up: close all open files
    fclose(myfile);
    fclose(output_file);

    return 0;
}

Key Changes Explained

  • Added a count variable to track how many temperature readings we process, so the average stays accurate no matter how many data points you have.
  • Fixed the fscanf format specifier to %f for reading float values.
  • Moved the average calculation outside the loop, so it runs once after all data is read.
  • Added a check for count > 0 to avoid dividing by zero if no valid data is read.
  • Added fclose(myfile) before exiting if the output file fails to open, preventing resource leaks.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:43:38