English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I have this code:

int readConfig(char *IP, int *p, char Myfile[]){
char dir[32];
char pto[32];
char c='a';
FILE *fp;
int i=0;

if((fp=fopen(Myfile,"r"))==NULL){
return -1;
}
while(c!=EOF && c!='\n'){
c=getc(fp);
if(c!=EOF && c!='\n'){
dir[i++]=c;

}
}

i=0;
c='a';

while(c!=EOF && c!='\n'){
c=getc(fp);
if(c!=EOF && c!='\n'){
pto[i++]=c;
}
}

*puerto=atoi(pto);
strcpy(IP, dir);
return 0;
}

and the file contains this information: 255.255.255.255
5555

Well, when I print the IP value, this is the result
IP: 255.255.255.255fhv���

How can I do for fix it??? I want that only print: IP: 255.255.255.255

Thanks!!!!

2007-11-15 15:07:18 · 3 answers · asked by yo 1 in Computers & Internet Programming & Design

3 answers

Cap the string (nul terminate) like so:

while(c!=EOF && c!='\n')
{
c=getc(fp);
if(c!=EOF && c!='\n'){
pto[i++]=c;
}

pto[i]='\0'; //cap it now!

That bad print out you've got is a classic/common result of printing a non nul-terminated string...

2007-11-15 15:29:47 · answer #1 · answered by gene_frequency 7 · 0 1

You need to null terminate your strings or write by count (ie. string length)

2007-11-15 15:13:40 · answer #2 · answered by mdigitale 7 · 0 0

memset your variable before filling it

2007-11-15 15:09:58 · answer #3 · answered by Chris 4 · 0 0

fedest.com, questions and answers