Marla
Marla

Reputation: 101

Can't write into a text file with for loop in c

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.

Upvotes: 3

Views: 5871

Answers (1)

Nik
Nik

Reputation: 1870

Each time you use FILE *fp = fopen("resultat.txt", "w"); what this does is delete the existing file and create a blank file for writing. What you're looking for is FILE *fp = fopen("resultat.txt", "a"); //a not w!. This will open the existing file and append content. If a file does not exist, one will be created. See this reference.

"w" - Creates an empty file for writing. If a file with the same name already exists, its content is erased and the file is considered as a new empty file.

"a" - Appends to a file. Writing operations, append data at the end of the file. The file is created if it does not exist.

Also heed @Serge's advice about not opening the file for each record. Just open it once in the main and use the file handle to write to it. To make your current code work, you can do this:

void write_file(char *result[], int len) {
   FILE *fp = fopen("resultat.txt", "a");//open for append
   if (fp == NULL){
       perror("resultat.txt");
       exit(1);
   }
   for (int i=0; i < len; i++) {
       fprintf(fp, "%s\n", result[i]);
   }
   fclose(fp);
}

Upvotes: 5

Related Questions