【发布时间】:2015-02-22 15:02:01
【问题描述】:
我的文本文件是 IP_CONFIG.txt
"192.168.128.3" IP_CS
"192.168.128.2" IP_HM
"192.168.128.1" IP_OB
"192.168.128.4" IP_AS
"127.0.0.1" IP_RS
"127.0.0.1" IP_RS_D
"1901" PORT_CS
"1901" PORT_HM
"1901" PORT_OB
"3567" PORT_AS
"4444" PORT_RS
"7777" PORT_RS_D
我的代码是
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXWORDS 30
int main(){
FILE *fp;
int i=0, j;
char *words=NULL,*word=NULL,c;
char *allwords[MAXWORDS];
if ((fp=fopen("IP_CONFIG.txt","r"))==NULL){
printf("Error Opening File\n");
exit(1);}
while ((c = fgetc(fp))!= EOF){
if (c=='\n'){ c = ' '; }
words = (char *)realloc(words, ++i*sizeof(char));
words[i-1]=c;}
word=strtok(words," ");
i=0;
while(word!= NULL && i < MAXWORDS){
//printf("%s\n",word);
allwords[i] = malloc(strlen(word));
strcpy(allwords[i], word);
word = strtok(NULL," ");
i++;
}
printf("\nNow printing each saved string:\n");
for (j=0; j<i; j++){
printf("String %d: %s\n", j, allwords[j]);
}
char * IP_CS = allwords[0];
char *IP_HM = allwords[2];
char *IP_OB = allwords[4];
char *IP_AS = allwords[6];
char *IP_RS = allwords[8];
char *IP_RS_D = allwords[10];
int PORT_CS = atoi(allwords[12]);
int PORT_HM = atoi(allwords[14]);
int PORT_OB = atoi(allwords[16]);
int PORT_AS = atoi(allwords[18]);
int PORT_RS = atoi(allwords[20]);
int PORT_RS_D = atoi(allwords[22]);
printf("The IPs are \n %s\n %s\n %s\n %s\n %s\n %s\n",IP_CS,IP_HM,IP_OB,IP_AS,IP_RS,IP_RS_D);
printf("The PORTSs are \n %d\n %d\n %d\n %d\n %d\n %d\n",PORT_CS,PORT_HM,PORT_OB,PORT_AS,PORT_RS,PORT_RS_D);
exit(0);
}
我已经解决了正确获取 IP 地址的问题,但我无法解决端口问题。因为它应该是在我的其他程序中使用的整数值,因此我使用了 atoi。但为什么我的输出只有零......而不是1901,3567等......(下面是输出)
Now printing each saved string:
String 0: "192.168.128.3"
String 1: IP_CS
String 2: "192.168.128.2"
String 3: IP_HM
String 4: "192.168.128.1"
String 5: IP_OB
String 6: "192.168.128.4"
String 7: IP_AS
String 8: "127.0.0.1"
String 9: IP_RS
String 10: "127.0.0.1"
String 11: IP_RS_D
String 12: "1901"
String 13: PORT_CS
String 14: "1901"
String 15: PORT_HM
String 16: "1901"
String 17: PORT_OB
String 18: "3567"
String 19: PORT_AS
String 20: "4444"
String 21: PORT_RS
String 22: "7777"
String 23: PORT_RS_D
The IPs are
"192.168.128.3"
"192.168.128.2"
"192.168.128.1"
"192.168.128.4"
"127.0.0.1"
"127.0.0.1"
The PORTSs are
0
0
0
0
0
0
如何获得文本文件中描述的确切端口号。谢谢
【问题讨论】:
-
编写一个测试程序来了解
atoi()的工作原理,哪个输入需要,哪个不需要。 -
我强烈建议使用
strtol而不是atoi。atoi有几个明显的缺陷,其中最重要的是,如果它解析一个大于 INT_MAX 的数字,它会导致未定义的行为。