I know that this is an old post, but the accepted one does not apply to cases where cout is sent to a program or file, and this is the top of my search queries. The following will handle both tubular and non-pigmented stdout with slightly different behavior.
#include <iostream> #include <functional> #include <stdio.h> #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #define _isatty isatty #define _fileno fileno #endif const std::function<void(const size_t&)> progress_printer(_isatty(_fileno(stdout)) == 1 ? [](const size_t& i) { std::cout << "\rNumber " << i << std::flush; } : [](const size_t& i) { static std::ios::off_type last(-1); if(last != -1) std::cout.seekp(last, std::ios::beg); last = std::cout.tellp(); std::cout << "Number " << i << std::endl; } );
This is not tested on windows, but should work. What he does is determine if the file descriptor is or is tty. If so, then he simply writes '\ r' if pos has not changed since his last print or a new line. If it is not a newline, it searches for the last place after printing. A.
It behaves differently for files than for tty. For a file, if something outputs a stream between prints, it can overwrite some or all of what was written even after a newline. For ttys, it simply overwrites the characters at the beginning of the current line.
Erroneous
source share