C# has a neat feature of being able to write to a memory stream using the MemoryStream object.
I’m looking for similar functionality from C using a FILE* pointer.
I want to be able to sprintf() but with the added functionality of having C remember “where I was” in the buffer I’m writing to.
There’s also an ugly hack which works with plain ISO-C: You can use
fopen()to open a null file (/dev/nullon *nix,NULon Windows) and set the array as the file’s buffer viaThis should work fine as long as
fflush()isn’t called anywhere in the code. Also, the programmer has to explicitly take care of the string delimiter.I don’t really see a need to do this, though: As
snprintf()returns the number of characters written, it’s trivial to keep track of a buffer’s position.One can even write a function to automagically resize the buffer on overflow: bufprintf.c
The function’s prototype is
An example program could look like this: