Reading a string into a char array in C

I am trying to read a C file that has a list of IP addresses in the following form.

1 121.20.35.8 5634
2 179.105.43.24 2345
3 122.45.36.102 5096
4 28.105.63.41 8081
5 128.20.6.250 1864

I am trying to write the IP address to the corresponding index. Although the corresponding index may not be in order. As in the case, a file of this type is quite possible.

 3 122.45.36.102 5096
 1 121.20.35.8 5634
 4 28.105.63.41 8081
 2 179.105.43.24 2345
 5 128.20.6.250 1864

I allocated an array to store addresses

    char** servers = malloc(sizeof(char*)*10);
    for (int i = 0; i < 10; ++i)
    {
        servers[i] = malloc(sizeof(char)*(MAX_IP + 1));
    }

And after reading the file using this code. MAX_IP here - line 255.255.255.255

   static const char filename[] = "file.txt";
   FILE *file = fopen ( filename, "r" );
   char line [MAX_IP + 10];
   while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
    {
       //split the line into index and IP address and store the IP   address in the relevant index
    }
      fclose ( file );

So now I want to read the file in such a way as to split the string into index and IP address and save the IP address in the corresponding index. Need a little help regarding the most effective way to solve it.

+4
source share
1 answer
while ( fgets ( line, sizeof line, file ) != NULL )
{ int idx, port; char ip[MAX_IP + 1];
  sscanf(line, " %d %s %d", &idx, ip, &port);
  strncpy(servers[idx-1], ip, MAX_IP + 1);
}

But, of course, if you are not sure about the correct input file, you should add error checking.

EDIT: " ", , , , . :

int idx, port; char ip[MAX_IP + 1];
while (3 == fscanf(file, " %d %s %d", &idx, ip, &port))
   memcpy(servers[idx-1], ip, MAX_IP + 1);

, memcpy , strcpy, , ip-...

+2

Source: https://habr.com/ru/post/1614912/


All Articles