下面是在linux程序中如何查看一个网卡名是否存在的算法源码
#define PROCBUFSIZ 1024
#define _PATH_PROC_NET_DEV "/proc/net/dev"
static char * interface_name_cut (char *buf, char **name)
{
char *stat;
/* Skip white space. Line will include header spaces. */
while (*buf == ' ')
buf++;
*name = buf;
/* Cut interface name. */
stat = strrchr (buf, ':');
*stat++ = '\0';
return stat;
}
int check_interface_fromproc(char *interface)
{
FILE *fp;
char buf[PROCBUFSIZ];
struct interface *ifp;
char *name;
/* Open /proc/net/dev. */
fp = fopen (_PATH_PROC_NET_DEV, "r");
if (fp == NULL)
{
printf("open proc file error\n");
return -1;
}
/* Drop header lines. */
fgets (buf, PROCBUFSIZ, fp);
fgets (buf, PROCBUFSIZ, fp);
/* Only allocate interface structure. Other jobs will be done in
if_ioctl.c. */
while (fgets (buf, PROCBUFSIZ, fp) != NULL)
{
interface_name_cut (buf, &name);
if(strcmp(interface,name)==0)
return 1;
}
fclose(fp);
return 0;
}
算法也算比较漂亮,更重要的是学习其中的书写格式(代码中空格的使用方法)