Skip to contentSkip to conversation

make sscanf honor %n at end of input string

PATCH New Johannes Berg 1 participant 1 message Mar 1, 2007

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 make sscanf honor %n at end of input string

I was playing with some code that sometimes got a string where a %n match should have been done where the input string ended, for example like this:

  sscanf("abc123", "abc%d%n", &a, &n);

However, the scanf function in the kernel doesn't convert the %n in that case because it has already matched the complete input after %d. This patch changes that.

---
Shrug. My use case for this collapsed, but I figured having scanf doing that correctly might be a good thing.

 lib/vsprintf.c |    9 +++++++++
 1 file changed, 9 insertions(+)
lib/vsprintf.c +9 -0
@@ -825,6 +825,15 @@ int vsscanf(const char * buf, const char
 			break;
 		str = next;
 	}
+
+	/* Now we've come all the way through so either the input string or
+	 * the format ended. In the former case, there can be a %n at the
+	 * current position in the format that needs to be filled. */
+	if (*fmt == '%' && *(fmt+1) == 'n') {
+		int *i = (int *)va_arg(args,int*);
+		*i = str - buf;
+	}
+
 	return num;
 }