我一個問題,讀/來自文件編寫和查看正確的輸入信號:不能從一個文件複製/讀取正確的模式列表
// LOAD THE LIST FROM THE FILE
struct elemento *caricalista(struct elemento *p) {
struct elemento *punt;
FILE * utenti = fopen ("miarubrica.txt", "r");
char nome[MAX];
char cognome[MAX];
char telefono[MAX];
char mail[MAX];
if (utenti == NULL) {
printf("non ho caricato gli utenti");
} else {
while (!feof(utenti)) {
if (p != NULL) {
punt = (struct elemento *)malloc(sizeof(struct elemento));
fscanf(utenti, "%s", nome);
puts(nome);
fscanf(utenti, "%s", cognome);
puts(cognome);
fscanf(utenti, "%s", telefono);
puts(telefono);
fscanf(utenti, "%s", mail);
puts(mail);
strcpy(punt->nome, nome);
strcpy(punt->cognome, cognome);
strcpy(punt->telefono, telefono);
strcpy(punt->mail, mail);
punt->pun = p;
} else if (p == NULL) {
p = (struct elemento *)malloc(sizeof(struct elemento));
fscanf(utenti, "%s", nome);
fscanf(utenti, "%s", cognome);
fscanf(utenti, "%s", telefono);
fscanf(utenti, "%s", mail);
strcpy(p->nome, nome);
strcpy(p->cognome, cognome);
strcpy(p->telefono, telefono);
strcpy(p->mail, mail);
p->pun = NULL;
punt = p;
}
}
}
fflush(utenti);
fclose(utenti);
return(punt);
}
// SAVE THE LIST
int salva(struct elemento *p) {
FILE *stream = fopen("miarubrica.txt", "w");
while (p != NULL) {
// Scrive sul file
fprintf(stream, "%s ", p->nome);
fprintf(stream, "%s ", p->cognome);
fprintf(stream, "%s ", p->mail);
fprintf(stream, "%s \n", p->telefono);
p = p->pun;
}
fflush(stream);
fclose(stream);
return;
}
這寫我(例如)
pippo disney 02345432 [email protected]
在miarubrica.txt
,但是當我與閱讀列表(它的工作原理)的方法讀它,我看到
pippo disney 02345432 [email protected]
pippo disney 02345432 [email protected]
兩次的外殼。怎麼了?
在第一次迭代中,新條目將指向「p」。在第二次迭代中,新條目也將指向「p」。另外,如果文件是空的,函數將返回NULL,但也許它應該返回'p'。 – MRAB 2012-07-13 17:26:16
謝謝,我已修復 – 2012-07-13 17:33:24
感謝Viktor和MRAB – myself 2012-07-13 18:01:32