Can';t在c中使用for循环写入文本文件
我在将字符串写入txt文件时遇到问题。我的行每次都会被覆盖。我使用Can';t在c中使用for循环写入文本文件,c,for-loop,malloc,c-strings,writefile,C,For Loop,Malloc,C Strings,Writefile,我在将字符串写入txt文件时遇到问题。我的行每次都会被覆盖。我使用 gcc-Wall-o filename.c进行编译,并/filename.txt执行。 txt文件总是只有一行(最后一行)如何保存所有记录 我有一个CSV文件,其中包含城市名称和居民数量,我需要筛选城市名称和最少居民数量 到目前为止,我尝试的是: ..... void write_file(char *result[], int len) { FILE *fp = fopen("resultat.txt", "w");
gcc-Wall-o filename.c
进行编译,并/filename.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;
}
。。。。。
无效写入文件(字符*结果[],整数长度){
文件*fp=fopen(“resultat.txt”,“w”);
如果(fp==NULL){
perror(“resultat.txt”);
出口(1);
}
对于(int i=0;i每次使用文件*fp=fopen(“resultat.txt”,“w”);
这样做的目的是删除现有文件并创建一个空白文件进行写入。您要查找的是文件*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);
}
void write_文件(char*result[],int len){
FILE*fp=fopen(“resultat.txt”,“a”);//打开以进行追加
如果(fp==NULL){
perror(“resultat.txt”);
出口(1);
}
对于(int i=0;i
最好只在循环前打开文件,然后在循环后关闭。