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

标签 c for-loop malloc c-strings writefile

我在将字符串写入 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 不是 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);
}

关于无法用c中的for循环写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47005374/

相关文章:

python - 额外参数在 Python 中的这个 for 循环中意味着什么?

c++ - std::malloc 的奇怪段错误

c - FUSE 程序中的内存分配是如何工作的?

c - C链表结构中的未知类型名称

代码不显示返回值

c - 我是否需要在关键部分使用 volatile 关键字进行内存访问?

javascript - 找不到Java错误的原因和解决方案

c - Spin Loop 在缓存一致性方面的开销

python - Pyhonic 使用 if 语句来处理应用于分块列表的不等式

c - c中没有堆吗?