String Stream in C

Said picture Said · Aug 14, 2010 · Viewed 19.8k times · Source
print2fp(const void *buffer, size_t size, FILE *stream) {

 if(fwrite(buffer, 1, size, stream) != size)
  return -1;

 return 0;
}

How to write the data into string stream instead of File stream?

Answer

cmaster - reinstate monica picture cmaster - reinstate monica · Jun 15, 2013

There is a very neat function in the posix 2008 standard: open_memstream(). You use it like this:

char* buffer = NULL;
size_t bufferSize = 0;
FILE* myStream = open_memstream(&buffer, &bufferSize);

fprintf(myStream, "You can output anything to myStream, just as you can with stdout.\n");
myComplexPrintFunction(myStream);    //Append something of completely unknown size.

fclose(myStream);    //This will set buffer and bufferSize.
printf("I can do anything with the resulting string now. It is: \"%s\"\n", buffer);
free(buffer);