我将尝试使用C语言读取一个文件,其中包含以下形式的IP地址列表。
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
我想把IP地址写入相关的索引中。虽然相关的索引可能不是按顺序排列的。例如,这种类型的文件是很常见的。
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
我已经分配了一个数组来保存地址
char** servers = malloc(sizeof(char*)*10);
for (int i = 0; i < 10; ++i)
{
servers[i] = malloc(sizeof(char)*(MAX_IP + 1));
}
使用以下代码读取文件。这里的MAX_IP是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 );
现在我想以一种方式读取文件,将行分割为索引和IP地址,并将IP地址存储在相关索引中。需要一些帮助来确定最有效的方法。
topology
。这是打字错误吗?应该是servers[I]
等等吗? - Fiddling Bitsint index = atoi(strtok(line, " ")) - 1; strcpy(servers[index], strtok(NULL, " "));
- Spikatrix