0

I'm working on a basic SIC assembler and one of the features that I'm trying to implement is that during a dump function, if the program generates more than a page of text on the console, it would prompt the user to press a key before continuing.

My dump function reads out the hex values of a range of addresses in memory.

0possum0
  • 3
  • 1
  • You have plenty of choice. For example a loop that continues until the user pressed a key, or use signals to handle that (with `wait();`), and so on... – Jean-Marc Zimmer Dec 04 '18 at 10:02
  • 1
    On POSIX systems, the easiest way is to pipe its output through `more`. Or on systems that have it, `less`. e.g. `FILE *outfd = popen("less", "w");`. i.e. let another program figure out terminal handling and all that. – Peter Cordes Dec 04 '18 at 10:10

2 Answers2

3

First you need to define what a "page" is. Then you will know how many lines are available. Then when printing you stop to get input every X lines (where X is the number of lines per page) before continuing printing the next X lines.

Because reading input will block until the user presses the Enter key (normally) then it will seem like your program pauses.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

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.)

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847