News for hackers. Stuff that matters.
Re:It Can Happen to You by froh on Thursday March 04, 2021 @01:48PM (#26346445)
scanf and printf have complementary format specifiers, which can make maintaining serialization and parsing of regular data a breeze...

the proper remedy is to simply wrap the string to parse with fmemopen(3), which makes the temporary FILE object explicit and persistent for the whole parse, and needs just one strlen call.

https://news.ycombinator.com/item?id=26343149

Re:It Can Happen to You by abetlen on Thursday March 04, 2021 @02:05PM (#26346672)
Cool trick, thanks for sharing. I don't get why there isn't a suitable snscanf function that takes the buffer length as an argument and returns the number of bytes parsed?
Re:It Can Happen to You by froh on Thursday March 04, 2021 @04:05PM (#26348305)
fmemopen takes the buffer length, and there is no need to have the buffer \0 terminated, so instead of strlen you can also just give the buffer size.

The number of bytes parsed can be fetched with the scanf %n format specifier.