0
votes

Using Visual Studio IDE, writing in C. Program is reading in a basic .txt file, converting from Fahrenheit to Celsius, and writing to new .txt file Why wont it find the .txt file? Here is my code:

#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");

}

here's where the .txt file is

this is the error code i received

2
You are not checking whether fopen succeeds or not. Looks like the fopen for the result has failed. - kaylum
And please don't post text messages as images. Paste it as text into the question so that others can more easily copy it for referencing in comments/answers. - kaylum
even if i check if it successfully opens, that will not change why it is not successful. Why is it not finding the .txt file? - Destreation
The file name that you pass to fopen is relative to the current working directory. When debugging, there's a project setting that allows you to point the current working directory to whatever directory you like. You can also change the current working directory from within your program (using chdir on unix-like systems). If the file that you want to open is not in the current working directory, then you need to specify the full path to the file, e.g. fopen("c:\\projects\\TempRecorder\\temperature.txt","r");. - user3386109

2 Answers

2
votes

I named the file "temperature.txt" and is was already a .txt file, so the file name was actually "temperature.txt.txt". Small mistake, big problem. Thanks for your help guys.

0
votes

The executable that runs is in the Debug folder (in this case), so temperature.txt needs to be in that folder, or it needs to be "..\temperature.txt" or similar passed into fopen().