Oh what does that mean in c?

if ( sscanf( line, "%[^ ] %[^ ] %[^ ]", method, url, protocol ) != 3 )... 

This format above is very strange, what does it do?

+6
source share
3 answers

This line tries to read 3 lines that do not contain a space, separated by spaces, in the method, url, protocol, and if it cannot read 3, it will then go into the if block.

+7
source

[] is a scan. If you tell %[abcd] then the input string with only a or b or c or d will be considered. The line will end when the first occurrence of any other character that is not a character in curly brackets.

^ inside [] used to indicate the compliment of a set inside braces. As in the format string %[^abcd] , only all characters will be accepted except a, b or c or d.

therefore, in %[^ ] space followed by ^ indicates that the format string will accept any combination of characters in the string that does not have a space.

A format string "%[^ ] %[^ ] %[^ ]" will correspond to a string containing three components separated by spaces. Each of the components will contain a sequence of characters in which there is no space.

The function returns the number of successfully entered and assigned input elements, which may be less than provided, or even zero in case of an early match.

Thus, the above function will return 3 only if and only if all three components are read, i.e. the input line has three sections and for each section three arrays of method , url and protocol were populated.

+3
source

scanf is a function that reads data from a string and returns the number of items successfully read.

So, scanf analyze line to find 3 lines containing a space and separated by a space, and place these 3 lines in the next 3 variables ( method , url , protocol ).

Then, if he parsed 3 arguments, he would go into the if block.

0
source

Source: https://habr.com/ru/post/888650/


All Articles