Reputation: 504
I have a problem parsing in c with sscanf
I read a text on console with one function called read_line()
char cm1[100],cm2[100],cm3[100]
printf("Enter command:");
read_line(var_text);
/*var_text = cat /etc/passwd | cut -f1 d: | sort */
int num = sscanf(var_text,"%s | %s | %s",cm1,cm2,cm3);
Ok if i write in var_text cat | cut | sort
in cm1 return cat in cm2 return cut and in cm3 return sort, but if i write cat /etc/passwd | cut -f1 d: | sort
, cm1 return cat and cm2 and cm3 none...
I'm made a shell in c, and i need the commands and atributes
Thx for all, and sorry for that bad english :)
Upvotes: 1
Views: 637
Reputation: 122001
The %s
format specifier will stop processing at the first whitespace character. In the case of:
cat /etc/passwd | cut -f1 d: | sort
it will be the space after the cat
at which the first %s
will end. The format specifier then expects a |
which does not exist and cm2
and cm3
are not populated. You could use a scanset to achieve this:
if (3 == sscanf(var_text, "%99[^|]| %99[^|]| %99s", cm1, cm2, cm3))
{
}
Note use of width specifier to prevent buffer overrun and checking of return value from sscanf()
to ensure all target variables were populated.
The format specifier %99[^|]
is stating read at most 99 characters (one less than the target buffer size to accomodate the null terminator) until a |
character is encountered.
See demo at http://ideone.com/Cz1Qef .
Upvotes: 4