简体   繁体   中英

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?

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){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM