我正在尝试从文件中拆分像 127.0.0.1 这样的 IP 地址:
使用以下 C 代码:
pch2 = strtok (ip,".");
printf("\npart 1 ip: %s",pch2);
pch2 = strtok (NULL,".");
printf("\npart 2 ip: %s",pch2);
IP 是一个字符 ip[500],它包含一个 ip。
打印时将 127 作为第 1 部分打印,但作为第 2 部分打印 NULL?
有人能帮我吗?
编辑:
整体功能:
FILE *file = fopen ("host.txt", "r");
char * pch;
char * pch2;
char ip[BUFFSIZE];
IPPart result;
if (file != NULL)
{
char line [BUFFSIZE];
while(fgets(line,sizeof line,file) != NULL)
{
if(line[0] != '#')
{
pch = strtok (line," ");
printf ("%s\n",pch);
strncpy(ip, pch, strlen(pch)-1);
ip[sizeof(pch)-1] = '\0';
//pch = strtok (line, " ");
pch = strtok (NULL," ");
printf("%s",pch);
pch2 = strtok (ip,".");
printf("\nDeel 1 ip: %s",pch2);
pch2 = strtok (NULL,".");
printf("\nDeel 2 ip: %s",pch2);
pch2 = strtok(NULL,".");
printf("\nDeel 3 ip: %s",pch2);
pch2 = strtok(NULL,".");
printf("\nDeel 4 ip: %s",pch2);
}
}
fclose(file);
}