繁体   English   中英

C fscanf解析带空格的字符串

[英]C fscanf to parse string with whitespace

我想解析一些这样的字符串:

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

我不需要上两行! 我的代码是这样,但我可以得到目标字段!

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

但是我得到的str1始终为NULL! 我能怎么做?

您尚未为str1分配内存。 那是核心问题。 scanf正在读取未初始化的内存,这将导致未定义的行为。

更新资料

正如@BLUEPIXY在评论中指出的那样,您还需要更改

while(num1=1){

while(num1==1){

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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