CoderFarmer
CoderFarmer

Reputation: 23

C fscanf to parse string with whitespace

I want to parse some string like this:

Chain FW_USER_IN (0 references)
pkts      bytes target     prot opt in     out     source               destination         
   0        0 ACCEPT     all  --  *      *       0.0.0.0/0            192.168.10.12
   0        0 ACCEPT     all  --  *      *       0.0.0.0/0            192.168.10.12

I needn't top two line! My code is like this,but i can get destination field!

FILE *handle;
char *str1;
int num1;
handle = popen("iptables -t mangle -x -v -L FW_USER_IN -n","r");

while (('\n' != fgetc(handle)) && !feof(handle));
while (('\n' != fgetc(handle)) && !feof(handle));
num1 =1;
while(num1=1){
    num1 = fscanf(handle,"%*d %*d %*s %*s %*s %*s %*s %*s %s",str1);
    printf("str1:%s\n",str1);
}  
fclose(handle);

but I got the str1 always is NULL! How can I do?

Upvotes: 0

Views: 123

Answers (1)

R Sahu
R Sahu

Reputation: 206567

You have not allocated memory for str1. That's the core problem. scanf is reading into uninitialized memory, which leads to undefined behavior.

Update

As @BLUEPIXY pointed out in a comment, you also need to change

while(num1=1){

to

while(num1==1){

Upvotes: 2

Related Questions