简体   繁体   English

fwrite,但是在C中用字符串代替文件

[英]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. 我正在编写一个C程序来从相机中获取JPEG帧并用它做各种各样的事情。 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): 它非常适合将帧写入stdout,但我真正需要的是这样的东西(“swrite”就像fwrite ,而不是char而不是文件):

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). 不幸的是,没有swrite功能(至少不是我能找到的)。 So... 所以...

Are there any functions similiar to an "swrite" function? 有没有类似“swrite”功能的功能?

or 要么

How can I use the process_frame function with printf (and therefore sprintf ) instead of fwrite ? 如何将process_frame函数与printf (因此使用sprintf )而不是fwrite

a char is just a single character. char只是一个字符。 What you mean is a char buffer; 你的意思是一个char缓冲区; and lo! 而且! your p is already one. 你的p已经是一个了。 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. 只需使用(char*)p (将您的void指针转换为char指针),或者将p指向的内容memcpy到您选择的char缓冲区。

Deamentiaemundi raises a good point: you probably pass p as const void* for a reason; Deamentiaemundi提出了一个很好的观点:你可能将p作为const void*传递出来是有原因的; if you plan to modify the data, you should memcpy the contents, definitely. 如果你打算修改数据,你肯定应该记住内容。

Under the hood, it seems your pointer p is just a big array of bytes. 在引擎盖下,似乎你的指针p只是一个很大的字节数组。 You can cast it to a char array and use it: 您可以将其强制转换为char数组并使用它:

char *jpegframe = (char *) p;

If you'd like to modify the frame, you might want to allocate some more memory and copy it in: 如果您想修改框架,可能需要分配更多内存并将其复制到:

static char* process_frame(const void *p, int size) {
    char* jpegframe = malloc(size);
    memcpy(jpegframe, p, size);

    /* Do the processing... */

    return jpegframe;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM