Friday, May 21, 2010

[c programming] fscanf() problem?

Hey guys,





im having trouble reading a text file containing these two lines:


127.0.0.1


3247





into a program using the following code:





char *server_ip; /*"127.0.0.1"; get this from a file*/


unsigned short server_port; /*= 3247; get this from a file*/








char *filename = "server_details.txt";


FILE *fp = fopen(filename, "r");





if(!fp)


{


printf("fopen() failed");


}


else


{


printf("lol\n");


fscanf(fp, "%s\n%d", server_ip, %26amp;server_port);


}


fclose(filename);





It throws the following error:


'The variable 'server_ip' is being used without being defined'





Has anyone got any idea for this?

[c programming] fscanf() problem?
you've used a char pointer. create a char array then pass the address.





char server_ip[16];





fscanf(fp,"%s\n%d",%26amp;server_ip,%26amp;server_...





note: you dont have to use %26amp; before array name. you can simply pass the name itself.





Tell me if it works.
Reply:One of mine:





char buf[350];


int wrfiles;


int grafmbytes;


int sizes;





fscanf(infile, "%s %d %s %d %15c %d", buf, %26amp;wrfiles, buf, %26amp;grafmbytes, buf, %26amp;sizes);





All on one line - next line:





fgets(buf, 16, infile);
Reply:Use two lines:


fscanf( fp, "%s\n", server_ip );


fscanf( fp, "%d", %26amp;server_port );


No comments:

Post a Comment