How can I implement ‘tee’ programmatically in C?

You could popen() the tee program. Or you can fork() and pipe stdout through a child process such as this (adapted from a real live program I wrote, so it works!): void tee(const char* fname) { int pipe_fd[2]; check(pipe(pipe_fd)); const pid_t pid = fork(); check(pid); if(!pid) { // our log child close(pipe_fd[1]); // Close unused … Read more

Is there a guarantee of stdout auto-flush before exit? How does it work?

This is accomplished by these two sections in the C++ language specification: [basic.start.main] A return statement in main has the effect of leaving the main function and calling exit with the return value as the argument. and [lib.support.start.term] The function exit has additional behavior in this International Standard: … Next, all open C streams with … Read more

Redirect stdin and stdout in Java

You’ve attempted to write to the output stream before you attempt to listen on the input stream, so it makes sense that you’re seeing nothing. For this to succeed, you will need to use separate threads for your two streams. i.e., import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Scanner; public class … Read more

Print LF with Python 3 to Windows stdout

Python 3 already configures standard I/O in binary mode, but it has its own I/O implementation that does newline translation. Instead of using print, which requires a text-mode file, you could manually call sys.stdout.buffer.write to use the binary-mode BufferedWriter. If you need to use print, then you’ll need a new text I/O wrapper that doesn’t … Read more

C restore stdout to terminal

#include <unistd.h> … int saved_stdout; … /* Save current stdout for use later */ saved_stdout = dup(1); dup2(my_temporary_stdout_fd, 1); … do some work on your new stdout … /* Restore stdout */ dup2(saved_stdout, 1); close(saved_stdout);

Redirect both cout and stdout to a string in C++ for Unit Testing

std::stringstream may be what you’re looking for. UPDATE Alright, this is a bit of hack, but maybe you could do this to grab the printf output: char huge_string_buf[MASSIVE_SIZE]; freopen(“NUL”, “a”, stdout); setbuf(stdout, huge_string_buffer); Note you should use “/dev/null” for linux instead of “NUL”. That will rapidly start to fill up huge_string_buffer. If you want to … Read more