Few things.
First, you should use fclose ().
Secondly, your code needs fscan () every line in the file. Not only before the while () loop, but in each while loop you need fscan () for the next iteration.
Thirdly, you do not calculate the average temperature, you calculate the sum of all the temperatures found. Fix this by changing "t_tot" to "(t_tot / found)" in your last printf ().
Finally, I'm not sure why you are not getting any result. Is your input like "myprogram file.txt Milano"? It works for me. Anyway, here is your (edited) code back:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main (int argc, char *argv[]) { int r, line = 0, found = 0; float temp, t_tot = 0; char loc[32]; FILE *fp; fp = fopen(argv[1], "r"); if (fp == NULL) { printf ("Error opening the file\n\n'"); exit(EXIT_FAILURE); } else { if (argc == 3) { r = fscanf(fp, "%f %s\n", &temp, loc); while (r != EOF) { line++; if (r == 2) { if(strcmp(argv[2], loc) == 0) { t_tot += temp; found++; } } else printf ("Error, line %d in wrong format!\n\n", line); r = fscanf(fp, "%f %s\n", &temp, loc); } printf ("The average temperature in %s is: %.1f\n\n", argv[2], (t_tot / found)); } fclose(fp); } }
source share