On POSIX systems, the easiest way is to pipe its output through more
. Or on systems that have it, less
.
FILE *outfd = popen("less", "w");
and use that instead of stdout
. popen(3)
is specified by POSIX. So is more
, but you might want to try less
first. Or better, use getenv("PAGER")
before falling back to more
.
Let another program figure out terminal handling and all that instead of trying to roll your own.
Some non-POSIX systems, like Windows, also have pager programs you can use. I think Windows even has a more
program, but IDK if it has a popen
function in any standard library outside of cygwin.
To redirect stdout
to a pipe, you could use more low-level POSIX functions like dup2
(search on SO for examples).
But I don't think you can do it mostly portably with just popen
. In the GNU C library (glibc), you can assign to stdout
, e.g. stdout = popen(...);
But other C implementations may not support that: stdout
can be a macro that doesn't support being assigned to. (See the glibc manual's Standard Streams page.)