开发者

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 开发者_StackOverflow社区data into string stream instead of File stream?


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);


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜