Warm tip: This article is reproduced from stackoverflow.com, please click
c pipe posix less-unix

Print with less(1) from C

发布于 2020-04-13 09:36:09

I would like to print a big matrix of data which I have in a linked list. It doesn't fit into a terminal (80 lines), so it is inconvenient to print it with standard printing functions; and less is already invented, so I wouldn't want to be reinventing it using ncurses; so I want to pass some printfd lines to less.

My first guess would be to write to a file, and then system("less -S file");, and then delete the file.

A more complicated solution would be to rewrite less so that its main() is converted to a less() function that I can call from C, and instead of a filename string I could provide it with a file descriptor or a stream.

Is there any way that doesn't involve needing to create a file and also not needing to rewrite (part of) less?

Questioner
Cacahuete Frito
Viewed
56
Jonathan Leffler 2020-02-03 07:21

You could consider using POSIX functions popen() and pclose().

You'd use:

FILE *fp = popen("less", "w");

if (fp != NULL)
{
    …write output to fp…
    pclose(fp);
}
else
    …report error…

Note that the pclose() will wait for less to exit. If you want to, you can capture the return value from pclose() and analyze it. See How to detect if shell failed to execute a command after popen()? for discussion of this.