【发布时间】:2017-05-08 20:02:54
【问题描述】:
我目前正在尝试从 Linux 文件“/proc/net/dev”中获取网络接口名称。我有两个问题。首先,我可以通过从第 3 行到文件末尾编写这段代码来获取它:
char buffer[100], word[10];
fgets(buffer, 100, fp);
sscanf(buffer, "%s %*[:] %*s", word);
但问题是我得到带有冒号的字符串(lo:eth0:eth1:)。我怎样才能以我在屏幕上显示的方式获得它们。
第二个问题是为什么我在以下代码中遇到分段错误:
#include <stdio.h>
#include <stdlib.h>
#define NETFILE "/proc/net/dev"
static char **interface_names;
int counting_lines()
{
FILE *fp = fopen(NETFILE, "r");
int i = 0;
char buffer[200];
while (fgets(buffer, sizeof(buffer), fp) != NULL)
{
i++;
}
fclose(fp);
return i;
}
void do_malloc()
{
int i;
int lines = counting_lines() - 2;
interface_names = (char **)malloc(lines * sizeof(char *));
for (i = 0; i < lines; i++)
{
interface_names[i] = (char *)malloc(10 * sizeof(char));
}
}
void free_malloc()
{
int i;
for (i = 0; i < (counting_lines() - 2); i++)
{
free(interface_names[i]);
}
free(interface_names);
}
void get_interface_names()
{
FILE *fp = fopen(NETFILE, "r");
int i = -2;
char buffer[100];
while (!feof(fp))
{
if (i < 0)
{
i++;
continue;
}
else
{
fgets(buffer, 100, fp);
sscanf(buffer, "%s %*[:] %*s", interface_names[i]);
i++;
}
}
fclose(fp);
}
int main()
{
do_malloc();
get_interface_names();
printf("%s\n", interface_names[0]);
printf("%d\n", counting_lines());
free_malloc();
return EXIT_SUCCESS;
}
【问题讨论】:
-
每个问题一个问题。
-
while (!feof(fp))总是无法检测到最后一项。您最终会在列表末尾找到一个重复项。 -
改用
strsep()。 -
@EdHeal 如果是这样,你的系统就有大问题了。
标签: c segmentation-fault malloc