-1

I know that (in C++) there are several methods which allow the redirection of the output/input to a file and which also allow it to be displayed at the console. However, as far as I am aware, there is no way to do both simultaneously. I haven't found any existing library functions for this purpose. Looking at all of the questions on this topic, a function like this seems to be useful. But why is this task virtually impossible? What are the processes going on in the background?

ten1o
  • 165
  • 5
  • 3
    you can write a function that writes its argument to a file and to the stdout. Why do you think it is impossible? – 463035818_is_not_an_ai Jan 20 '23 at 16:21
  • @463035818_is_not_a_number as far as the functions that I have seen, none of them allow this to be accomplished at the same time. – ten1o Jan 20 '23 at 16:23
  • 1
    "Virtually impossible"? A tee stream is minimally writable in a dozen-ish lines of code; searching for "c++ write to file and console" provides a fair amount of ideas (including existing implementations). – Dave Newton Jan 20 '23 at 16:24
  • 2
    For what its worth Boost has [`boost::iostreams::tee`](https://www.boost.org/doc/libs/1_39_0/libs/iostreams/doc/functions/tee.html) which operates like linux's `tee` which can write to both cout and a file. Here's an example of usage https://stackoverflow.com/questions/999120/c-hello-world-boost-tee-example-program – Cory Kramer Jan 20 '23 at 16:24
  • You may have to do one then the other. Although you may be able to use DMA to transfer data to the file while writing to the console. – Thomas Matthews Jan 20 '23 at 16:27

1 Answers1

2

It is not impossible to do this. You can output quasi-simultaneously to the console and to another stream, e.g. a filestream.

Confer to the documentation of ofstream and cout, look at the examples at the bottom of the pages.

You would need to call the corresponding functions (i.e. cout or write) after each other at a point in your code, where you would like to have them.

Since those would be executed in sequence (and not really simultaneously) you would have to wait until one of those functions returned. (For lengthy outputs it might take a while). In order to achieve a higher level of parallelization you might consider multi-threading techniques. For example, having one thread writing the data to console and another writing to a file. But make sure to avoid data-races, e.g. by duplicating the data or using constructs like lock_guards, mutexes, condition variables, atomics, or semaphores.

Zacryon
  • 639
  • 6
  • 11