Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print to a buffer or file reusing code

Tags:

c

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

like image 224
ldonoso Avatar asked Jul 30 '12 15:07

ldonoso


People also ask

How to reuse a code in Python?

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).

What is function explain code reuse?

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.

What enables us to reuse the same block of code?

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.


1 Answers

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;
}
like image 192
Flexo Avatar answered Nov 11 '22 15:11

Flexo