I am trying to store a file .txt
in type variables char
in C, the problem is that the result when compiling prints the last line twice and I don't understand the reason.
- In the file
.txt
I have the following:
123.22.0.212 255.255.0.0
2.169.73.5 255.255.0.0
2.50.10.36 255.255.192.0
- Compile result is as follows:
123.22.0.212 255.255.0.0
2.169.73.5 255.255.0.0
2.50.10.36 255.255.192.0
2.50.10.36 255.255.192.0
- C code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * archivo = fopen("direcciones.txt", "rb");
if(archivo == NULL)
{
perror("Error en la apertura del archivo");
return 1;
}
/*leyendo caracter por caracter*/
char ip[12];
char mask[12];
while( feof(archivo) == 0)
{
fscanf(archivo, "%s%s", &ip, &mask);
printf("%s %s\n", ip, mask);
}
fclose(archivo);
printf("\n\nSe ha leido el archivo correctamente...");
return 0;
}
First, what you don't ask but is equally wrong:
Your test data is:
And your variables to store them
However, by my count, it
255.255.192.0
's 13 characters long . Your variables are poorly dimensioned. And for that matter, I255.255.255.255
would need 16 bytes . 15 for the characters themselves, and 1 more for the0
end.We continue:
In C, there is no concept of a buffer or continuous-memory-area . A formation or arrangement does not exist as such . Roughly speaking, it's a favor the compiler is doing you by allocating a chunk of memory for you... and giving you a pointer to that zone .
In other words:
ip
andmask
are already pointers . In fact, if you use&ip
or&mask
, the compiler will show you a nice warning:Ok, now your problem: Very simple, it
feof( )
checks the eof flag of the file, but the eof flag is only set on performing an operation , never before:feof( )
checks that everything is okay.feof( )
checks that everything is okay.fscanf( )
it doesn't read anything (thus keeping the last thing you read). Now the flag is seteof
.feof( )
detects the problem.Your code, corrected, would look like this: