redirect stdout/stderr to function in C -
i want redirect stdout , stderr function , write simple code. fprintf ok when use printf without \r, stream passed terminal!
#include <stdio.h> static ssize_t file_write(void *c, const char *buf, size_t size) { file * pfile; pfile = fopen ("output.txt","w"); fprintf(pfile, "%s", buf); fclose (pfile); return size; } void redirect() { file *stream; stream=fopencookie(null, "w", (cookie_io_functions_t) {(ssize_t) 0, file_write, 0, 0}); setbuf(stdout, null); stdout = stream; setbuf(stderr, null); stderr = stream; } int main() { redirect(); fprintf(stderr,"1-stderr test\n"); fprintf(stdout, "2-stdout test\n"); printf("3-printf r test\n\r"); printf("4-printf without r test\n"); return 0; }
file "output.txt":
1-stderr test
2-stdout test
3-printf r test
terminal output:
$ ./sample
4-printf without r test
you can't "redirect" standard input from, or standard output function in program.
you can create pair of pipes , replace standard input , output these pipes, , have function (possibly in thread or child process) use other end of pipes communicate function.
you can of course use e.g. setvbuf
change buffers of stdin
, stdout
pair of buffers provide, can read directly from, or write directly buffers other memory buffer (i.e. array). not recommend though, it's frail , prone errors.
however in case seems want writing stdout
should go file. in case (like use of pipes) there no standard c way of handling it, need use operating system specific functionality. if you're on posix platform (like linux or osx) can tell operating system duplicate underlying file descriptor file, , stdout_filno
(which file descriptor used stdout
) duplicate file descriptor of file opened. writes stdout
written file. need use the dup2
system call.
Comments
Post a Comment