Is there something like PHP ob_start for C?
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.
开发者_Go百科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
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.
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;
}
精彩评论