无法用c中的for循环写入文本文件

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

我在将字符串写入 txt 文件时遇到问题。我的台词每次都会被覆盖。我用
gcc -Wall -o filename filename.c 编译,./filename 10 Berlin cat resultat.txt 执行。 txt文件总是只有一行(最后一行)如何保存所有记录。

我有一个包含城市名称和一些居民的 CSV 文件,我需要过滤城市名称和最少的居民。

到目前为止我尝试了什么:

.....
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;
}

在 for 循环之外使用 write_file() 函数可以得到 null 值。如果有人对如何优化代码有想法,请发表评论或回答。

每次使用 FILE *fp = fopen("resultat.txt", "w"); 时,它所做的就是删除现有文件并创建一个空白文件用于写入。您要查找的是 FILE *fp = fopen("resultat.txt", "a"); //a not w!。这将打开现有文件并附加内容。如果文件不存在,将创建一个。参见 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.

同时注意@Serge 关于不要为每条记录打开文件的建议。只需在 main 中打开一次并使用文件句柄写入即可。要使您当前的代码正常工作,您可以这样做:

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);
}