PDA

View Full Version : [C] problema lettura da file


alderaan79
18-04-2010, 16:37
Ciao a tutti,
sto facendo un progetto in C e ho un problema nella lettura da file.
Il contenuto del file è il seguente:

new U 5 9 25.6875
?
new F 2 4 198.5000
?
new E 4 7 55.4375
kaboom U
?
!

deve leggere riga per riga identificando new, ?, kaboom e ! come comandi per eseguire le relative funzioni.

Il mio main è il seguente:

int main (int argc, char *argv[]){
FILE *p;
int i;
char name;
int part, fin;
float alt, risp;
crea();
if(argc<2){;}
else{
p=fopen(argv[1], "r");
if(p == NULL){
perror("Errore apertura file");
exit(1);
}
}
printf("NEW NEW YORK\n\n");
while(p != NULL){
char tmp[8];
while(fgets(tmp, 2, p) != "!"){
if((fgets(tmp, 3, p) != '\0') || (strcmp(tmp, "new"))){
fscanf(p, " %c %d %d %f", &name, &part, &fin, &alt);
printf("\n%c %d %d %f\n\n", name, part, fin, alt);
inserisci(name, part, fin, alt);
}
if((fgets(tmp, 1, p) != '\0') || (strcmp(tmp, "?"))){
risp=skyline();
printf("\nSkyLine: %f\n", risp);
fgets(tmp, 3, p)== NULL;
}

if((fgets(tmp, 6, p) != '\0') || (strcmp(tmp, "kaboom"))){
fscanf(p, "%c", &name);
elimina(name);
fgets(tmp, 3, p)== NULL;

}
fclose(p);
printf("\n");
system("PAUSE");
return 0;
}

}
}

il problema è che non cicla nel modo corretto nel senso che legge il primo new e svolge correttamente la funzione collegata, legge il primo ? e svolge correttamente la funzione collegata ma poi ignora i successivi new e ? per considerare, invece, correttamente il comando kaboom e il comando !.
Qualcuno può cortesemente spiegarmi dove sbaglio?
Grazie millle

lupoxxx87
18-04-2010, 18:01
1. usa il tag per inserire codice
2. indenta il codice
3. il regolamento vieta di chiedere la risoluzione di progetti per esami universitari


...cmq....prendendo dal K&R...

char *fgets(char *s, int size, FILE *stream);

fgets() reads a line from the stream and stores it inside the *s buffer.
fgets() reads, in the best case, (size-1) characters if it doesn't reach a '\n' or EOF character, and puts a '\0' character as a last character of the buffer.

mi chiedo quindi come fai a immagazzinare il carattere '?' in un buffer che può tenere solo il carattere '\0'.

poi imho non ha logica confrontare un puntatore a caratteri, qual'è il valore restituito dalla funzione, con un carattere;
così come non ha senso una valutazione cortocirtuitata in un if dove il primo argomento è (quasi) sempre true.


while(fgets(tmp, 2, p) != "!")
if((fgets(tmp, 3, p) != '\0') || (strcmp(tmp, "new")))
if((fgets(tmp, 1, p) != '\0') || (strcmp(tmp, "?")))
if((fgets(tmp, 6, p) != '\0') || (strcmp(tmp, "kaboom")))


ps: un consiglio....studia C prima di dare l'esame...

Teo@Unix
18-04-2010, 18:01
però metti il codice tra i tag CODE, altrimenti così è poco leggibile.