[linux]linux c实现mac地址写入文件,实现删除和增加操作
功能描述
c实现mac地址写入文件,实现删除和增加操作
代码实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int find_and_del_mac_from_old_file(char *mac)
{
char tmpbuf[8192] = {0};
char buf[8192] = {0};
char cmd[9000] = {0};
char *p = NULL;
char *q = NULL;
char result[8192] = {0};
int ret = 0;
FILE * fp = fopen("./hostapd_mac","r+");
if(fp == NULL)
{
printf("error open : ./hostapd_mac \n");
return 0;
}
else
{
fgets(buf,sizeof(buf),fp);
printf("buf=%s\n",buf);
if(p = strstr(buf,mac))
{
printf("p=%s strlen(p)=%d\n",p,strlen(p));
printf("buf=%s \n",buf);
if(q = strstr(p,";"))
{
q = q + 1;
strncpy(result,buf,strlen(buf) - strlen(p));
printf("q=%s\n",q);
printf("p=%s\n",p);
printf("result=%s\n",result);
ret = 1;
}
memset(cmd,0,sizeof(cmd));
snprintf(cmd, sizeof(cmd),"echo -n \"%s%s;\" > ./hostapd_mac", result,q);
system(cmd);
printf("delete mac is %s\n",mac);
}
fclose(fp);
}
return ret;
}
int add_black_mac_to_file(char *mac)
{
char tmpbuf[8192] = {0};
char buf[8192] = {0};
char cmd[9000] = {0};
char *p = NULL;
FILE * fp = fopen("./hostapd_mac","a+");
if(fp == NULL)
{
printf("error open : ./hostapd_mac \n");
return 0;
}
else
{
fgets(buf,sizeof(buf),fp);
if(p = strstr(buf,mac))
{
printf("mac had existed in file\n");
fclose(fp);
return 1;
}
else
{
mac[18] = '\0';
printf("buf=%s mac=%s\n",buf,mac);
sprintf(tmpbuf,"%s%s;",buf,mac);
printf("tmpbuf=%s\n",tmpbuf);
if(strlen(tmpbuf) > 8100)
{
fclose(fp);
system("rm -rf ./hostapd_black_mac");
return 1;
}
snprintf(cmd, sizeof(cmd),"echo -n \"%s\" > ./hostapd_mac", tmpbuf);
system(cmd);
}
fclose(fp);
}
return 0;
}
int main(int argc, char*argv[])
{
char mac[18] = {0};
if(argc == 3)
{
strncpy(mac,argv[1],17);
printf("mac=%s\n",mac);
if(strcmp(argv[2],"add") == 0)
add_black_mac_to_file(mac);
if(strcmp(argv[2],"del") == 0)
find_and_del_mac_from_old_file(mac);
printf("parm error\r\n");
}
return 0;
}