Mar*_*rla 2 c malloc for-loop 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;
}
Run Code Online (Sandbox Code Playgroud)
使用write_file()for循环外部的函数给出了null值.如果有人知道如何优化代码,请发表评论或回答.
每次使用FILE *fp = fopen("resultat.txt", "w");它时,都会删除现有文件并创建一个空白文件进行写入.你在寻找什么FILE *fp = fopen("resultat.txt", "a"); //a not w!.这将打开现有文件并附加内容.如果文件不存在,将创建一个文件.请参阅此参考.
"w" - 创建一个用于写入的空文件.如果已存在具有相同名称的文件,则会删除其内容,并将该文件视为新的空文件.
"a" - 附加到文件.编写操作,在文件末尾附加数据.如果文件不存在,则创建该文件.
还要注意@ 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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2061 次 |
| 最近记录: |