【发布时间】: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