0

我正在尝试从文件中拆分像 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 是一个字符 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);
}
4

3 回答 3

3

你做一个

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) - 1is sizeof(char*) - 1,在 32 位机器上只有 3 个字节。这对应于 3 个字符,即“127”,这与您观察到的第二个strtok()给出 NULL 一致。

于 2012-11-25T17:02:04.863 回答
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
于 2012-11-25T16:59:00.793 回答
0

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

于 2012-11-25T17:04:02.360 回答