Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Stream in C

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?

like image 546
Said Avatar asked Aug 13 '10 22:08

Said


2 Answers

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);
like image 62
cmaster - reinstate monica Avatar answered Nov 08 '22 00:11

cmaster - reinstate monica


Use sprintf: http://www.cplusplus.com/reference/cstdio/sprintf/

Here's an example from the reference:

#include <stdio.h>

int main ()
{
  char buffer [50];
  int n, a=5, b=3;
  n = sprintf(buffer, "%d plus %d is %d", a, b, a+b);
  printf("[%s] is a string %d chars long\n", buffer, n);
  return 0;
}

Output:

[5 plus 3 is 8] is a string 13 chars long

Update based on recommendations in comments:

Use snprintf as it is more secure (it prevents buffer overflow attacks) and is more portable.

#include <stdio.h>

int main ()
{
  int sizeOfBuffer = 50;
  char buffer[sizeOfBuffer];
  int n, a = 5, b = 3;
  n = snprintf(buffer, sizeOfBuffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a string %d chars long\n", buffer, n);
  return 0;
}

Notice that snprintf's second argument is actually the max allowed size to use, so you can put it to a lower value than sizeOfBuffer, however for your case it would be unnecessary. snprintf only writes sizeOfBuffer-1 chars and uses the last byte for the termination character.

Here is a link to the snprintf documentation: http://www.cplusplus.com/reference/cstdio/snprintf/

like image 21
Elias ringhauge Avatar answered Nov 07 '22 23:11

Elias ringhauge