I’m trying to make a simple command that pauses for user input. I think it’ll be useful in Bash scripts.
Here’s my code:
#include <stdio.h>
int main() {
char key[1];
puts("Press any key to continue...");
fgets(key,1,stdin);
}
It doesn’t even pause for user input.
I tried earlier to use getch() (ncurses). What happened is, the screen went blank and when I pressed a key, it went back to what was originally on the screen, and I saw:
$ ./pause
Press any key to continue...
$
It’s somewhat what I wanted. But all I want is the equivalent of the pause command in DOS/Windows (I use Linux).
From the GNU C Library Manual:
So,
fgets(key,1,stdin);reads 0 characters and returns. (read: immediately)Use
getcharorgetlineinstead.Edit: fgets also doesn’t return once
countcharacters are available on the stream, it keeps waiting for a newline and then readscountcharacters, so "any key" might not be the correct wording in this case then.You can use this example to avoid line-buffering: