I have an issue with writing strings into a txt file. My lines get overwritten every time. I use
gcc -Wall -o filename filename.c
to compile and ./filename 10 Berlin cat resultat.txt
to execute.
The txt file always has just one line (the last one) how can I save all the records.
I have a CSV file with city names and a number of residents, I need to filter for the City name and a minimum of residents.
What I tried so far:
.....
void write_file(char *result[], int len) {
FILE *fp = fopen("resultat.txt", "w");
if (fp == NULL){
perror("resultat.txt");
exit(1);
}
for (int i=0; i<len; i++) {
fprintf(fp, "%s\n", result[i]);
}
fclose(fp);
}
int main(int argc,char **argv) {
int anzahl = atoi(argv[1]);
char *string_array[100];
char *erste_zeile;
erste_zeile = (char *) malloc(1000 * sizeof(char));
char staedte[MAX_LAENGE_ARR][MAX_LAENGE_STR];
char laender[MAX_LAENGE_ARR][MAX_LAENGE_STR];
int bewohner[MAX_LAENGE_ARR];
int len = read_file("staedte.csv", staedte, laender, bewohner);
for (int i = 0; i < len; ++i){
if (strcmp(argv[2],laender[i])==0 && anzahl < bewohner[i]){
snprintf(erste_zeile, 100,"Die Stadt %s hat %d Einwohner\n",staedte[i],bewohner[i]);
string_array[0] = erste_zeile;
// counter++;
write_file(string_array,1);
}
}
free(erste_zeile);
return 0;
}
Using the write_file()
function outside of the for loop gives me null
values. If anybody has an idea how to optimize the code please leave a comment or answer.