Search code examples
cmdgetcharoutput-redirect

getchar() workaround in c/c++ in order to redirect output


I have an executable which is written in c++ and i run it in cmd.exe on Windows

When i run this executable and by looking at the source code, i can see that a use of getchar() function is made - The program asks the user to "click any key to continue" and i can see that getchar() is called so the program dosent continue until the user clicks any key.

My problem is that the program's output is too long so i want to redirect it to a file...(with the redirection character >)

So when i run the exe like this in cmd.exe:

prg > temp.txt

The program gets stuck, i assume that its because it waits for an input ( i tried clicking any key but it dosent work.)

When i run the program without redirecting it to a file, all works fine so long i press any key when prompted...

I would have just erased all getchar() calls but I CANNOT change the source code because i dont have all the resources in order to re-compile it.

Is there a workaround to my problem?


Solution

  • getchar typically uses buffered input. That is, from a user's perspective, it doesn't wait for any key, but rather waits for the user to press Enter.

    You should press Enter once for each getchar that the program does. Or alternatively, the first time it does getchar (though you can only guess when it is, because there is no prompt), enter a long string:

    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
    

    Once you press Enter, the subsequent 30 getchar invocations will get a, the next one will get \n, and the next one will hang, waiting for more input (but there will be no prompt).

    Another possible way you could make it work: redirect some input to your program:

    echo aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | prg > temp.txt
    

    Make sure you have enough input to satisfy all getchar calls.