I'd like to define two functions, fdump and sdump, to dump a struct 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 the two functions? One solution could be define sdump and then fdump based on it, e.i.:
void fdump(FILE* f, struct mystruct* param) {
char buffer[MAX];
sdump(buffer, MAX, param);
fprint(f, "%s", buffer);
}
But that solution wastes and intermediate buffer. Although maybe fprintf does the same. Other solution could be by means of preprocessing macros but it looks quite complicated. Please, any ideas?
Thanks in advance
And when it comes to reusing code in Python, it all starts and ends with the humble function. Take some lines of code, give them a name, and you've got a function (which can be reused). Take a collection of functions and package them as a file, and you've got a module (which can also be reused).
Code reuse is the practice of using existing code for a new function or software. But in order to reuse code, that code needs to be high-quality. And that means it should be safe, secure, and reliable. Developing software that fulfills these requirements is a challenge.
In programming, reusable code is the use of similar code in multiple functions. No, not by copying and then pasting the same code from one block to another and from there to another and so on. Instead, code reusability defines the methodology you can use to use similar code, without having to re-write it everywhere.
You can use fmemopen
to give you a file handle that points to a chunk of memory and then write just one version of your function that takes a file handle:
#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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With