char数组用strtok拆分ip

时间:2012-11-25 16:44:52

标签: c

我正在尝试从文件中分割出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是一个char 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);
}

3 个答案:

答案 0 :(得分:2)

你做了

strncpy(ip, pch, sizeof(pch) - 1);
ip[sizeof(pch)-1] = '\0';

这应该是

strncpy(ip, pch, strlen(pch));
ip[strlen(pch)] = '\0';

或更好,只是

strcpy(ip, pch);

因为sizeof(pch) - 1sizeof(char*) - 1,在32位机器上只有3个字节。这相当于3个字符,即“127”,这符合您的观察,第二个strtok()给出NULL。

答案 1 :(得分:1)

我使用了您的代码如下,它适用于我

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char ip[500] = "127.0.0.1";

int main() {
    char *pch2;
    pch2 = strtok (ip,".");
    printf("\npart 1 ip: %s",pch2);
    pch2 = strtok (NULL,".");
    printf("\npart 2 ip: %s",pch2);
    return 0; 
}

执行

linux$ gcc -o test test.c
linux$ ./test

part 1 ip: 127
part 2 ip: 0

答案 2 :(得分:0)

发现问题,Visual studio将0添加到指针,这与NULL相同......