Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print with less(1) from C

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?

like image 752
alx Avatar asked Oct 14 '25 07:10

alx


1 Answers

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.

like image 135
Jonathan Leffler Avatar answered Oct 17 '25 00:10

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!