在C语言中将一行读入字符数组

4
我将尝试使用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 Bits
是的,这是一个打字错误,已经更正。 - Antithesis
你有什么问题? - Jonathon Reinhart
@JonathonReinhart 已更新。 - Antithesis
“相关索引”是什么意思? - Fiddling Bits
尝试使用以下代码:int index = atoi(strtok(line, " ")) - 1; strcpy(servers[index], strtok(NULL, " ")); - Spikatrix
1个回答

2
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);
}

当然,如果您对输入文件的正确性不确定,那么应该添加错误检查。
编辑:既然您要求“高效的方法”,您可以一步完成读取,而不是先读取一行再解析它。您也可以这样做:
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);

注意,除非源字符串比缓冲区的大小要小得多(这在IP地址中很少发生),否则memcpy比strcpy更快...

1
你的编码规范是在 while 循环括号行上放置语句吗? - Fiddling Bits
@FiddlingBits 是的,我已经养成了尽可能在垂直方向上压缩代码的习惯,因为我受够了上下滚动屏幕来阅读我的代码...实际上,大多数屏幕都是宽屏的。我知道我几乎是唯一这样做的,但我认为它可读性良好,不会有任何问题。 - A.S.H

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接