tags:

views:

38

answers:

2

Hi,

I have a simple gateway listener which generates a log at the screen output via printf. I would like to record it so I can insert it in a mysql table.

printf("\nPacket received!! Decoding...");

I wonder if there is any fast way to do this is C.

In case there is, could I get both outputs at the same time?

Thanks

+2  A: 

I'm not aware of any function that does output buffering in C. But you can simulate one easily like:

char buffer[MAX_BUFFER_SIZE] = ""; // that buffers your output.
char temp[SOME_SUITABLE_MAX];

now everytime you are using printf, use a sprintf as follows:

sprintf(temp,"\nPacket received!! Decoding...");

and them append this string to the buffer

strcat(buffer,temp);

keep doing the sprintf followed by strcat for every message you want to buffer and once done buffer will have the buffered output.

codaddict
That was exactly what I was looking for provided I'll save the log in a mysql database. Thanks :)
echedey lorenzo
+1  A: 

Assuming by "record it" you mean you want to write it to a file, then yes, it's pretty easy. Unix has had a tee utility for years that would let you do something like:

gateway_listener | tee record_file

If you're running on a system that doesn't provide a tee by default, it should be pretty easy to find or compile one:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {

    FILE *outfile;
    int c;

    if ( argc < 2) {
        fprintf(stderr, "Usage: tee <out_file>\n");
        return EXIT_FAILURE;
    }

    if (NULL == (outfile = fopen(argv[1], "w"))) {
        fprintf(stderr, "Unable to open '%s'\n", argv[1]);
        return EXIT_FAILURE;
    }

    while (EOF != (c=getchar())) {
        putc(c, outfile);
        putchar(c);
    }

    fclose(outfile);
    return 0;
}
Jerry Coffin
Well redirecting the output to a file seems trivial, but what I really needed is to save the output to a mysql table. Thanks for your input and for custom tee which I'll take care of :D
echedey lorenzo