Hacker News new | past | comments | ask | show | jobs | submit login

For those of us who forgot this odd behavior:

%n: Print nothing, but writes the number of characters successfully written so far into an integer pointer parameter.




I'm just a perpetual amateur in C and I've never heard of this. TIL. Thanks.


Now promptly forget about it again, so you're never tempted to use it.


Perpetual amateur.

I like that because it describes me perfectly. Saving this.


That's frightening. Is there any legit use case for this in the real world that would stop, e.g., glibc from removing it altogether?


I got curious and looked through sources. I'm not sure where it was added, but it appeared between 4.3BSD and the 4.3BSD Tahoe edition according to the man pages. It did not seem to be present in System III. Searching for actual uses, I didn't find any that weren't testing the functionality (unit tests) or hacking the stack.


Perhaps you could print non-tabulated numbers until you run close to the end of line and be counting the characters with %n. Then you can print a new line, set your counter to zero, and continue.


You might want to know where in the output string different elements of your format string were placed. I've used %n with sscanf, but not *printf.


Some programs use it for formatting purposes. macOS enabled “no format strings from writable memory” a while back and it broke these.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: