I have this code to read integers from a file.
I used the same code to read doubles from another file
and worked perfectly, but this time the looping is
getting infinite. What could be? The file i’m reading
was written by a program, could be it? I don’t know
what does this mean but my OS says that the file is
binary. Well, any help will be appreciated. Thanks.
i=1;
cadeia = malloc ( i * sizeof(int) );
if (!cadeia){ //Avalia se a alocação de memória foi bem sucedida
printf("Problema na alocação de memória para cadeia.");
exit(0);
}
while ( !feof( arq_cadeia ) ){ /*Fazendo leitura e alocação de memória da matriz de transição*/
fscanf ( arq_cadeia , "%d" , ( cadeia+i-1 ) );
i++;
cadeia = realloc ( cadeia , i * sizeof( int ) );
if (!cadeia){ //Avalia se a alocação de memória foi bem sucedida
printf("Problema na alocação de memória para cadeia.");
exit(0);
}
printf("%d\n", *( cadeia+i-1 ));
}
Your hunch is right, if your file is in binary format
scanfcan’t read it. If you can’t see the numbers with a text editor (e.g., Notepad),scanfcan’t read them either.Your program has other problems, by the way: It’s terribly inefficient to realloc your entire array every time you read a number! The simplest thing would be to allocate so much space that you won’t need it all (don’t worry about the “waste”, as long as you don’t go way over the top). Second simplest is to measure the size of the file (you’ll need
stator some such) and estimate the number of integers in it. Third simplest, allocate enough for 10000 integers, and carefully check when you’re about to run out and allocate twice as much as you already had.