I recently created a video demonstration of how to do some work at the command line, but as I tried to record my video, I kept running into problems. I'm just not the kind of person who can type commands at a keyboard and talk about it at the same time. I quickly realized I needed a way to simulate typing, so I could create a "canned" demonstration that I could narrate in my video.
After doing some searching, I couldn't find a command on my distribution that would simulate typing. I wasn't surprised; that's not a common thing people need to do. So instead, I rolled my own program to do it.
Writing a program to simulate typing isn't as difficult as it first might seem. I needed my program to act like the echo
command, where it displayed output given as command-line parameters. I added command-line options so I could set a delay between the program "typing" each letter, with an additional delay for spaces and newlines. The program basically did this the following for each character in a given string:
- Insert a delay.
- Print the character.
- Flush the output buffer so it shows up on screen.
First, I needed a way to simulate a delay in typing, such as someone typing slowly, or pausing before typing the next word or pressing Enter. The C function to create a delay is usleep(useconds_t usec)
. You use usleep()
with the number of microseconds you want your program to pause. So if you want to wait one second, you would use usleep(1000000)
.
Working in microseconds means too many zeroes for me to type, so I wrote a simple wrapper called msleep(int millisec)
that does the same thing in milliseconds:
int
msleep (int millisec)
{
useconds_t usec;
int ret;
/* wrapper to usleep() but values in milliseconds instead */
usec = (useconds_t) millisec *1000;
ret = usleep (usec);
return (ret);
}
Next, I needed to push characters to the screen after each delay. Normally, you can use putchar(int char)
to send a single character to standard output (such as the screen), but you won't actually see the output until you send a newline. To get around this, you need to flush the output buffer manually. The C function fflush(FILE *stream)
will flush an output stream for you. If you put a delay()
before each fflush()
, it will appear that someone is pausing slightly between typing each character.
from Linux Journal - The Original Magazine of the Linux Community https://ift.tt/2SeITuI
via IFTTT
No comments:
Post a Comment