char array split ip with strtok

Posted by user1480139 on Stack Overflow See other posts from Stack Overflow or by user1480139
Published on 2012-11-25T16:44:51Z Indexed on 2012/11/25 17:04 UTC
Read the original article Hit count: 189

Filed under:

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);
}

© Stack Overflow or respective owner

Related posts about c