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] != '#')
{
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);
}
You do a
This should be
or better yet, just
because
sizeof(pch) - 1issizeof(char*) - 1, which is just 3 bytes on a 32 bit machine. This corresponds to 3 chars, namely “127”, which is in line with your observation the secondstrtok()giving NULL.