String Stream in C

2019-01-19 11:37发布

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?

2条回答
爷、活的狠高调
2楼-- · 2019-01-19 12:14

simply use sprintf http://www.cplusplus.com/reference/cstdio/sprintf/

example from the refference:

#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 snprinft as it is more secure (prevents buffer overflow attacks) and is 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 seconds 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.

And just to piss off everyone from the embbed and security department, here is a link to http://www.cplusplus.com/reference/cstdio/snprintf/

查看更多
Root(大扎)
3楼-- · 2019-01-19 12:34

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);
查看更多
登录 后发表回答