I need to make a programming code in C, in which I ask the user for the name of a city, present in the first file (cities.csv), and I have to remove the id from the inserted city. Then, this id must match another id, present in a second file (meteorologia.csv), and then edit the meteorological information, present in the second file. I've been doing a lot of research and with some help, I got the code below. However, when compiled, everything in the second file is replaced by the data in the first file. Could someone help me?
#define TAM_STR 100
typedef struct city_t{
char city_id[TAM_STR];
char city_name[TAM_STR];
char county_name[TAM_STR];
char district_name[TAM_STR]; } city_t;
typedef struct meteo_t{
char meteo_id[TAM_STR];
char meteo_city_id[TAM_STR];
char tempt_max[TAM_STR];
char tempt_min[TAM_STR];
char humidity[TAM_STR];
char preassure[TAM_STR];
char date[11]; } meteo_t;
int editInfo(){
char city[100];
struct city_t INFO;
struct meteo_t DATA;
printf("Qual e a cidade: ");
scanf("%[^\n]%*c", city);
FILE* stream = fopen("cidades.csv", "r");
FILE* meteo =fopen ("meteorologia.csv","w");
if("cidades.csv" == NULL || "meteorologia.csv" == NULL)
{
printf("Nao e possivel abrir o ficheiro\n");
return -1;
}
char line[1024];
while (fgets(line, 1024, stream) != NULL)
{
sscanf(line, "%s", INFO.city_name);
if(strcmp(city, INFO.city_name) == 0)
{ //pelo que me disseram, falta aqui um while
sscanf(line, "%s,%s,%s,%s,%s", DATA.tempt_max, DATA.tempt_min, DATA.humidity, DATA.preassure, DATA.date);
printf("Introduza o valor da temperatura maxima: ");
scanf("%s", DATA.tempt_max);
printf("Introduza o valor da temperatura minima: ");
scanf("%s", DATA.tempt_min);
printf("Introduza o valor da humidade: ");
scanf("%s", DATA.humidity);
printf("Introduza o valor da pressao: ");
scanf("%s", DATA.preassure);
printf("Introduza a data correspondente, no formato AAAA-MM-DD: ");
scanf("%s", DATA.date);
fprintf(meteo, "%s,%s,%s,%s,%s", DATA.tempt_max, DATA.tempt_min, DATA.humidity, DATA.preassure, DATA.date);
printf("Informacao alterada com sucesso!");
fclose(stream);
fclose(meteo);
}
else
{
fputs(line, meteo);
}
}
}
The cities.csv file has 152 rows and 4 columns in this format:
id_cidade,cidade,concelho,distrito
such as:
98,Porto,Porto,Porto
The weather file has 152 rows and 7 columns in this format:
id_meteo,id_cidade,temp_max,tem_min,humidade,pressao,data
such as:
98,98,9.5,0.3,62,1025,2018-02-12
Any help is welcome. Thank you!