简体   繁体   English

char数组用strtok分割ip

[英]char array split ip with strtok

I'm trying to split a IP address like 127.0.0.1 from a file: 我正在尝试从文件中拆分IP地址(例如127.0.0.1):

using following C code: 使用以下C代码:

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. IP是一个char ip [500],其中包含一个ip。

When printing it prints 127 as part 1 but as part 2 it prints NULL? 在打印时,它作为第1部分打印127,但作为第2部分打印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 你做一个

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

This should be 这应该是

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

or better yet, just 或者更好,只是

strcpy(ip, pch);

because sizeof(pch) - 1 is sizeof(char*) - 1 , which is just 3 bytes on a 32 bit machine. 因为sizeof(pch) - 1sizeof(char*) - 1 ,在32位计算机上只有3个字节。 This corresponds to 3 chars, namely "127", which is in line with your observation the second strtok() giving NULL. 这对应于3个字符,即“ 127”,这与您观察到的第二个strtok()给出NULL一致。

I used your code as following and it works for me 我使用您的代码如下,它对我有用

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

execution 执行

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

part 1 ip: 127
part 2 ip: 0

发现了问题,Visual Studio将0添加到指针,多数民众赞成与NULL相同...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM