Say input stream (stdin) has "abc" on it. I want to push back, say, 3 '*' chars to stdin to get something like "***abc". I was trying to use ungetc()
(I did ungetc('*', stdin)
) for this but I realized that it guarantees only 1 character pushback, and then it may fail. Is there any other way I could push 3 (or any known N) amount of characters back to stdin?

- 79
- 5
1 Answers
There is no portable way to accomplish this.
However, most implementation of the standard C library will allow multiple pushbacks, within reason. So in practice, it may not be a problem.
If you need an absolute guarantee, you'd need to write your own stdio implementation. That's certainly possible, since there are open source implementations which you could modify. But it's a lot of work. Alternatively, you could use the FreeBSD library, if it is available for your platform, since it does guarantee the possibility of repeated ungetc calls. (As far as I know, the GNU implementation also allows arbitrary ungetc calls. But the documentation doesn't guarantee that.)
Some libraries include non-standard interfaces like GNU's fopencookie, which let you create stdio streams with custom low-level read and write functions. Unfortunately, these do not help with this particular use case, which requires the ability to customise the implementation of stdio buffers. So that's a dead-end; I only mention it because it might seem plausible at first glance.

- 234,347
- 28
- 237
- 341