Search code examples
cless-unix

how print in c without jumping to end of text?


I'm very new to coding in general so please excuse any stupid things I say.

I am trying to print (in c) a rather long text using printf() but since it can't all fit on the screen it jumps to the end of the text and the beginning is not visible unless you scroll up. Is there an easy way to have it print the long text but stay at the beginning and allow the user to scroll down as they read before they put in the next command?


Solution

  • On Unix (including Linux and Mac), there are command line programs built in called more and less that does exactly what you describe. more is a program that simply waits for the user to press enter or space before showing the next page of output. less is slightly improved in that it allows vi editor keystrokes (such as j and k) to scroll up and down in the output.

    more is also available on the Windows command line as well. You might even be able to find a version of less for Windows as well.

    c:\users\selbie> your_program.exe | more
    
    $> ./your_program | less
    

    As to how to do this programmatically, that's a bit more difficult as it would involve measuring the console width and implementing your own scroll buffers. There might be open-source libraries that provide this functionality, but the console environment already has a solution for apps that produce long output.