-1

I want to print out text (from a file previously opened) until I press the key q. All of the methods I have tried pause my text being printed out. Is there a way to print the text while looking for a key press in C?

ex:

//after turning off canonical mode and echoing

char* output = "press q to stop this";

char ch;

while(ch = getchar()!= 'q')
{
    printf("%s\n",output);
}

It only prints the prompt after you enter a char. I want it to continue to print the prompt continuously.

Solved my problem with this webpage that I found: http://cc.byexamples.com/2007/04/08/non-blocking-user-input-in-loop-without-ncurses/

joeGV
  • 9
  • 2

3 Answers3

1

You can create a child process.

  • parent prints elem from file
  • child waiting user input
  • to stop execution you can use kill(getppid(), SIGTERM) to kill parent and exit(0) to kill child
Lluís M.
  • 80
  • 6
0

Based on jave.web's response in Wait for input for a certain time

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include<unistd.h>
#include<windows.h>


char waitForCharInput( int seconds ){
    char c = '_'; //default return
    while( seconds != 0 ) {
        if( _kbhit() ) { //if there is a key in keyboard buffer
            c = _getch(); //get the char
            break; //we got char! No need to wait anymore...
        }

        Sleep(1000); //one second sleep
        --seconds; //countdown a second
    }
    return c;
}

int main()
{
    FILE *fp = fopen("_filename_","r");
    char buffer[255];
    while(fgets(buffer, 255, (FILE*) fp))
    {
        printf("%s\n", buffer);
        char response = waitForCharInput(1);
        if(response == 'q')
            break;
    }
}
Community
  • 1
  • 1
lu5er
  • 3,229
  • 2
  • 29
  • 50
0

Found my answer here: http://cc.byexamples.com/2007/04/08/non-blocking-user-input-in-loop-without-ncurses/

I understand my question was too broad but this is how I solved my issue.

joeGV
  • 9
  • 2