Billy Billy - 3 months ago 14
C Question

fwrite, but to string instead of file in C

I'm writing a C program to get a JPEG frame from a camera and do various stuff with it. I have the following function:

static void process_frame(const void *p, int size) {
fwrite(p, size, 1, stdout);
}


It works great for writing the frame to stdout, but what I really need is something like this ("swrite" being like
fwrite
, but to a
char
instead of a file):

static char* process_frame(const void *p, int size) {
char* jpegframe;
swrite(p, size, 1, jpegframe);
return jpegframe;
}


Unfortunately, there is no swrite function (at least not that I could find).
So...

Are there any functions similiar to an "swrite" function?


or


How can I use the process_frame function with
printf
(and therefore
sprintf
) instead of
fwrite
?

Answer

a char is just a single character. What you mean is a char buffer; and lo! your p is already one. Just use (char*)p (cast your void pointer to a char pointer), or memcpy the things that p points to to the char buffer of your choice.

Deamentiaemundi raises a good point: you probably pass p as const void* for a reason; if you plan to modify the data, you should memcpy the contents, definitely.

Comments