无法打开文件求助: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.txton Windows — note the double backslashes to escape the character, or/home/yourname/Input_file.txton 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 recognizeInput_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.txtin 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:
- Wrong format specifier in
fscanf: You used%.2fto read the temperature, butfscanfdoesn’t accept precision specifiers for floats. Use%finstead —%.2fis only for output functions likeprintf/fprintf. - Incorrect average calculation: You’re dividing
sumTempby 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. - Hardcoded data count: Using
4as 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
countvariable to track how many temperature readings we process, so the average stays accurate no matter how many data points you have. - Fixed the
fscanfformat specifier to%ffor reading float values. - Moved the average calculation outside the loop, so it runs once after all data is read.
- Added a check for
count > 0to 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
相关产品推荐
相关产品推荐

