【问题标题】:Can't write into a text file with for loop in c无法在c中使用for循环写入文本文件
【发布时间】:2017-10-29 21:23:52
【问题描述】:

我在将字符串写入 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 值。如果有人知道如何优化代码,请发表评论或回答。

【问题讨论】:

  • 最好只在循环前打开文件,循环后关闭。

标签: c for-loop malloc c-strings writefile


【解决方案1】:

每次使用FILE *fp = fopen("resultat.txt", "w"); 时,它的作用是删除现有文件并创建一个空白文件用于写入。你要找的是FILE *fp = fopen("resultat.txt", "a"); //a not w!。这将打开现有文件并附加内容。如果文件不存在,将创建一个。见this reference

“w”- 创建一个用于写入的空文件。如果已存在同名文件,则删除其内容,并将该文件视为新的空文件。

“一个”- 附加到文件。写入操作,在文件末尾追加数据。如果文件不存在,则创建该文件。

还要注意@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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 2019-02-28
    • 2018-03-14
    • 2023-03-30
    • 1970-01-01
    • 2011-10-25
    • 2021-07-06
    相关资源
    最近更新 更多