【发布时间】:2016-08-05 02:03:15
【问题描述】:
使用Visual Studio IDE,用C编写。程序是读取一个基本的.txt文件,将华氏温度转换为摄氏温度,然后写入新的.txt文件 为什么找不到.txt文件?这是我的代码:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void)
{
double tempArray[30];
double temp;
double sum = 0;
int input_status;
int count = 0;
double convert;
FILE *infile, *outfile;
infile = fopen("temperature.txt", "r");
if (infile == NULL) {
perror("Failed: ");
return 1;
}
outfile = fopen("results.txt", "w");
int i = 0;
input_status = fscanf(infile, "%lf", &temp);
double max, min = temp;
while (input_status != EOF)
{
tempArray[i] = (temp - 32) * 5 / 9; ;
sum += tempArray[i];
fprintf(outfile, "%f \n", tempArray[i]);
if (tempArray[i] > max)
max = tempArray[i];
if (tempArray[i] < min)
min = tempArray[i];
count++;
i++;
input_status = fscanf(infile, "%lf", &temp);
}
double average = sum / count;
fprintf(outfile, "\n The average of the temperatures is %f \n", average);
fprintf(outfile, "\n The maximum of the temperatures is %f \n", max);
fprintf(outfile, "\n The minimum of the temperatures is %f \n", min);
fclose(infile);
fclose(outfile);
system("pause");
}
【问题讨论】:
-
您没有检查
fopen是否成功。结果的fopen似乎失败了。 -
请不要将短信作为图片发布。将其作为文本粘贴到问题中,以便其他人可以更轻松地复制它以在 cmets/answers 中引用。
-
即使我检查它是否成功打开,也不会改变它不成功的原因。为什么找不到 .txt 文件?
-
您传递给
fopen的文件名是相对于当前工作目录的。调试时,有一个项目设置允许您将当前工作目录 指向您喜欢的任何目录。您还可以在程序中更改当前工作目录(在类unix 系统上使用chdir)。如果您要打开的文件不在当前工作目录中,那么您需要指定文件的完整路径,例如fopen("c:\\projects\\TempRecorder\\temperature.txt","r");.
标签: c visual-studio compiler-errors