I have the following code in language C
, which tries to read a file:
- File
.txt
:
156.23.54.45 255.255.0.0
31.13.65.36 255.255.192.0
The first string I store in the variable char ip[16]
, which I then compare using the function strcmp
to check if the "ip" exists in the file I read previously. This makes it perfect, the problem is when returning the other variable called mask
. If I run printf
if it shows what I need, but when trying to return the value, it doesn't show anything when compiling (it compiles without errors by the way)
- Code in
C
:
char redes(){
FILE * archivo = fopen( "directorios.txt", "rb" );
if( archivo == NULL) {
perror( "Error en la apertura del archivo" );
exit(1);
}
char ip[16];
char mask[16];
while( 1 ) {
fscanf( archivo, "%s%s", ip, mask );
if( feof( archivo ) != 0 ) {
break;
}
if(strcmp(ip, "31.13.65.36") == 0){
// printf("La mascara es %s", mask);
return *mask;
}
}
fclose( archivo );
}
int main(){
char mascara = redes();
printf("%s", mascara);
}
In addition to those explained in Juan Carlos Guibovich 's answer , you MUST NOT return .
mask
mask
is an automatic variable. Its lifetime is limited to the time it spends within your roleredes( )
. Most likely, the compiler will show you a warning when compiling your code.Doing it the way you do will return a pointer to a memory area that may or may not contain what you expect. It's undefined behavior: either everything works... or you just get a bunch of garbage characters.
Normally, dynamic memory would be used to do what you intend (see
malloc( )
,calloc( )
,realloc( )
andfree( )
).Variables with static storage can also be used. This solution has some bugs and one advantage: it doesn't use dynamic memory .
Looking at your code, a possible solution would be to use a variable as a persistent buffer , so that it is filled the first time you call your function, so that, on successive times, we do not need to read from the file again, but directly return what we already have stored:
With this code, you can call your function
redes( )
as many times as you want . The file will be read only the first time .The thing is that mask is an array of 16 characters, so the name itself is already a pointer. Now you can access the values using pointer or array notation. For example: the first element of mask can be referenced as mask[0] or *mask, the second as mask[1] or *(mask+1).
From the above, if you want to return the mask of 16 you have to return a pointer or an array . You can do that by changing the data type of the networks function:
and in main change:
If you realize in the print you use a dry mask, that's why you take out the full mask. Already when it returns, it only returns the first byte
EDIT: . The variable declaration
mask
must also be changed. See answer from@Trauma
.