0
I need to make a programming code in C, in which I ask the user the name of a city, present in the first file (cities.csv), and I have to remove the id of the city inserted. Then this id has to match another id, present in a second file (meteorology.csv), and then edit the weather information, present in the second file. I’ve been doing a lot of research and with some help, I was able to get the code below. However, when I compile it, everything in the second file is overwritten with the data from 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.csv cities file has 152 rows and 4 columns in this format:
id_cidade,cidade,concelho,distrito
as an example:
98,Porto,Porto,Porto
The weather file has 152 lines and 7 columns, with this format:
id_meteo,id_cidade,temp_max,tem_min,humidade,pressao,data
as an example:
98,98,9.5,0.3,62,1025,2018-02-12
Any help is welcome. Thank you!
Thanks for your help! However, your code still doesn’t work on my program, and this time, it erases everything I have in the.csv weather file. The program compiles, but when I enter the city to search, the program stops running
– Jessijow Black