2012-11-25 58 views
0

我试图从一个文件分割像127.0.0.1一个IP地址:使用字符数组拆分IP与strtok的

下面的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); 
} 
+2

确定吗?我无法重现错误。尝试显示ip的初始化。 – effeffe

+0

它怎么能打印** NULL?你确定这个问题吗? –

+0

我已经添加了整个代码,我正在读取一个主机文件。不知道如何可以打印null ...:s – user1480139

回答

2

你做一个

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

这应该是

或更好,但只是

strcpy(ip, pch); 

因为sizeof(pch) - 1sizeof(char*) - 1,这是一个32位机器上仅有3个字节。这对应于3个字符,即“127”,这符合你的观察,第二个strtok()给出NULL。

+0

@ user1480139请参阅修改后的答案。 –

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 
0

发现问题,Visual Studio将0添加到指针并且与NULL一样...

+0

请看我的答案。 –

+0

我以为我发现它与我的测试,但它does not工作。我编辑了代码ey eyou说,仍然打印NULL – user1480139