char array split ip with strtok
- by user1480139
I'm trying to split a IP address like 127.0.0.1 from a file:
using following C code:
pch2 = strtok (ip,".");
printf("\npart 1 ip: %s",pch2);
pch2 = strtok (NULL,".");
printf("\npart 2 ip: %s",pch2);
And IP is a char ip[500], that containt an ip.
When printing it prints 127 as part 1 but as part 2 it prints NULL?
Can someone help me?
EDIT:
Whole function:
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] != '#')
{
//fputs(line,stdout);
pch = strtok (line," ");
printf ("%s\n",pch);
strncpy(ip, pch, sizeof(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);
//if(strcmp(pch,url) == 0)
//{
// result.part1 =
//}
}
}
fclose(file);
}