2016-03-29 10 views
-2

В моем коде здесь я читаю текстовый файл с именем input-temps.txt (этот файл загружен и помещается в папку проекта, над которым я работаю), который содержит 25 значений температуры, которые нужно читать за каждый день , Моя программа считывает эти значения и сохраняет их в массив. По завершении вычисления max, min и avg он записывает эти значения вместе с почасовой таблицей температур в выходной файл, который я назову output-temps.txt.Запись в файл error

Проблема с моим кодом здесь заключается в том, что при запуске файл не может быть найден. Я экспериментировал с другими циклами, но имел тот же результат. Что я ошибаюсь?

спасибо.

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

//function prototype 
void calc_results(int time[], int size); 
void read_temps(int temp[]); 

//set size of array as global value 
#define SIZE 25 

int main()  { 
    //Declare temperature array with size 25 since we are going from 0 to 24 
    int i, temp[SIZE]; 

    read_temps(temp); 
    //Temperature for the day of October 14, 2015 
    printf("Temperature conditions on October 14, 2015:\n"); 
    printf("\nTime of day\tTemperature in degrees F\n\n"); 

    for (i = 0; i < SIZE; i++) 
     printf("%d \t\t%d\n",i,temp[i]); 
    //call calc_results(temp, SIZE); 
    calc_results(temp, SIZE); 
    //pause the program output on console until user enters a key 
    return 0; 
} 

/*The method read_temps that takes the input array temp 
    and prompt user to enter the name of the input file 
    "input.txt" and then reads the temperatures from the file 
    for 24 hours of day */ 
void read_temps(int temp[])  { 

    char fileName[50]; 
    int temperature; 
    int counter=0; 

    printf("Enter input file name : "); 
    //prompt for file name 
    scanf("%s",fileName); 
    //open the input file 
    FILE *fp=fopen(fileName, "r"); 
    //check if file exists or not 
    if (fp=fopen("results.dat","r")== NULL)  { 
     printf("File could not be opened.\n"); 
     //if not exit, close the program 
     exit(0); 
    } 
    //read temperatures from the file input.txt until end of file is encountered 
    while(fscanf(fp,"%d",&temperature)!=EOF) { 
     //store the values in the temp array 
     temp[counter]=temperature; 
     //increment the counter by one 
     counter++; 
    } 
    //close the input file stream fp 
    fclose(fp); 
} 

void calc_results(int temp[], int size) { 
    int i, min, max, sum = 0; 
    float avg; 
    min = temp[0]; 
    max = temp[0]; 
    //Loop that calculates min,max, sum of array 
    for (i = 0; i < size; i++) { 
     if (temp[i] < min) { 
      min = temp[i]; 
     } 
     if (temp[i] > max) { 
      max = temp[i]; 
     } 
     sum = sum + temp[i]; 
    } 
    avg = (float) sum/size; 
    //open an external output file 
    FILE *fout=fopen("output.txt","w"); 
    //Temperature for the day of October 14, 2015 
    fprintf(fout,"Temperature conditions on October 14, 2015:\n"); 
    fprintf(fout,"\nTime of day\tTemperature in degrees F\n\n"); 
    //write time of day and temperature 
    for (i = 0; i < SIZE; i++) { 
     fprintf(fout,"%d \t\t%d\n",i,temp[i]); 
    } 
    printf("\nMin Temperature for the day is : %d\n", min); 
    printf("Max Temperature for the day is :%d\n", max); 
    printf("Average Temperature for the day is : %f\n", avg); 
    //write min ,max and avg to the file "output.txt" 
    fprintf(fout,"\nMin Temperature for the day is : %d\n", min); 
    fprintf(fout,"Max Temperature for the day is :%d\n", max); 
    fprintf(fout,"Average Temperature for the day is : %f\n", avg); 
    //close the output file stream 
    fclose(fout); 
} 
+0

Какой файл не найден? Входной файл или выходной файл? – Evert

+0

Мое первое предположение: вы должны распечатать, в какую директорию вы на самом деле пишете. Мой намек: есть разница между «./output.txt» и просто «output.txt». :-) –

+0

[это файл] (https://cluster13-files.instructure.com/courses/1172924/files/52804716/course%20files/temperatures.txt?download=1&inline=1&sf_verifier=8437ffa948329ef02f1f4b46afbc74b3&ts=1459218438&user_id=3964210), который не может быть найден, который является входом –

ответ

0

Чтобы проверить, существует ли файл, вам необходимо использовать функцию «access()». Для этого сначала включают в себя:

#include <unistd.h>   // For "access()" function 
#include <errno.h>   // For "errno" 
#include <string.h>   // For "strerror()" function 
// add your stuffs here ... 
// ..... 
// ..... 
int status = access(filename, F_OK); 
int saved_error = errno;    // For errno include <errno.h> 
if (status == -1) { 
    fprintf(stderr, "File Error: %s\n", strerror(saved_error)); 
    // For "strerror" include <string.h> 
    exit(EXIT_FAILURE); 
} 
// Now here file will exist and can be opened as: 
FILE *fptr = fopen(filename, "r"); 
saved_error = errno; // Read more about errno: "man errno" commend in linux 
// check for error 
if(fptr == NULL){ 
    fprintf(stderr, "File error: %s\n", strerror(saved_error); 
    exit(EXIT_FAILURE); 
} 
// Now access you file using fptr...