/*程序功能:获取配置文件中的IP字符串
程序目的:记录下来,免得以后重写了,不如意地方以后再改*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
int etc_file(char *file,char *buffer);//读取配置文件
int cut_ip(char *,char **);//分割并获取对应IP地址
int main()
{
char *buffer;
char **p;
int i;
buffer = (char *)malloc(1000);
}
p = (char **)malloc(sizeof(char *)*20);
/*分配二维指针空间*/
for(i=0;i<20;i++)
{
p[i] = (char *)malloc(sizeof(char)*16);
if(p[i] == NULL)
{
printf("分配内存失败!\n");
exit(0);
}
}
char *file = "a.txt";
if(etc_file(file,buffer))
{
buffer[strlen(buffer) - 2] = 0;
printf("ip str = %s\n",buffer);
if(!cut_ip(buffer,p))
{
/*do something*/
}
/*释放指针内存*/
for(i = 19; i > 1; i--)
{
free(p[i]);
}
free(p);
free(buffer);
return 0;
}
int etc_file(char *file,char *buffer)
{
FILE *fd;
fd = fopen(file,"rb");
if(fd != NULL)
{
while(1)
{
if(fgets(buffer,1000,fd))
{
char *s;
if((s = strstr(buffer,"host")))
{
strcpy(buffer,s+6);
return 1;
}
}
else
break;
}
}
return 0;
}
int cut_ip(char * str,char **p)
{
int i = 0,count = 0;
while(*(str + i) != '\0')
{
int j = 0 ,len = 0;
while((*(str + i +j) != ',') && (*(str + i +j) != '\0'))
{
*(*p + len) = *(str + i + j);
len++;
j++;
}
*(*p + len) = 0;
printf("p[%d] = %s\n",++count,*p);
*p++;
i = i + j + 1;
if(*(str +i -1) == '\0')
break;
}
return 0;
}
a.txt内容如下:
name="chenqin","jian"
host="192.168.137.1,192.168.137.2,192.168.137.123,192.168.137.
35"