Print to clipboard or code reuse

I would like to define two functions: fdump and sdump, to upload the structure to a file or to a buffer using fprintf and sprintf in each case.

Is there a way to define them without repeating the code in two functions? One solution could be to define sdump and then fdump on it, ei:

void fdump(FILE* f, struct mystruct* param) { char buffer[MAX]; sdump(buffer, MAX, param); fprint(f, "%s", buffer); } 

But this is a dissolution of waste and an intermediate buffer. Although perhaps fprintf does the same. Another solution might be to use preprocessing macros, but it looks rather complicated. Any ideas please?

Thanks in advance

+6
source share
1 answer

You can use fmemopen to give you a file descriptor that points to a piece of memory, and then write only one version of your function that takes a file descriptor:

 #include <stdio.h> void foo(FILE *fh) { fprintf(fh, "test\n"); } int main() { foo(stderr); char str[100]; FILE *mem = fmemopen(str, sizeof str, "w"); foo(mem); fclose(mem); fprintf(stdout, "%s", str); return 0; } 
+3
source

Source: https://habr.com/ru/post/921682/


All Articles