Your primary problem is that you do not initialize Num
to zero, so you get indeterminate (quasi-random) starting points for your counting.
You also have unnecessary includes, use feof()
unnecessarily, and have unnecessary code repetition because of that. (See also the discussion in the comments to the question.)
Your code should be more like this:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int Id_provincia;
struct fec
{
int dd;
int mm;
int aa;
} Fecha;
char Tipo_alerta;
} incendio;
int main(void)
{
const char filename[] = "Incendios_carga.dat";
FILE *archivo = fopen(filename, "rb");
if (archivo == NULL)
{
fprintf(stderr, "failed to open file '%s' for reading\n", filename);
exit(1);
}
incendio foco;
int Num = 0;
while (fread(&foco, sizeof(foco), 1, archive) == 1)
{
printf("el ID_Proviconcia es: %d\n", foco.Id_provincia);
Num++;
}
printf("la cantidad de regs son: %d\n", Num);
fclose(archive);
return 0;
}
The placement of braces is subjective — you can use 1TBS, but I prefer Allman. Just be consistent (and you were almost entirely consistent — the {
after the typedef
is on the wrong line for 00% consistency).
Print messages with a trailing newline. Print errors on stderr
, not stdout
. Avoid exiting a program silently when an error occurs. Report the name of the file that can't be opened. That usually means "use a variable (or #define
) to hold the filename so you can pass it to both fopen()
and fprintf()
". IMO, it is rarely correct to call fopen()
or any other file-opening function with a string literal for the file name because you need to repeat the string in the error message. Since you defined variable foco
just before the loop, I move the definition of Num
there too, initializing it to zero. I prefer programs to finish with return 0;
even though C99 says it isn't necessary. (I regard that as a bug in the standard, but it was done for conformity with C++98. I just don't use the (mis-)feature.)