Julien
Julien

Reputation: 91

How to print what's on the command line C

To build a chat, I have to send and receive messages. Currently, I am sending and receiving messages from the command line. When I receive a message while I was typing one, the received message is printed and I can't see what was typed before. I use the read()command to catch the user input.

Here is an example:

Let's suppose I want to send the message Hello World and that I receive a message after typing Hello Wor.

This is what happens :

$ Enter your message : Hello Wor
$ Somebody: This is a message 
$ Enter your message :

But Hello Wor is still on the command line: if I press the Delete Key, I will see Hello Wo. This is what I want :

$ Enter your message : Hello Wor
$ Somebody: This is a message 
$ Enter your message : Hello Wor

I would like to save what was typed before printing the received message and print it.

Upvotes: 1

Views: 185

Answers (1)

Dai
Dai

Reputation: 155035

Without using a terminal control API like curses or ncurses, you will need to change your program to work like-so:

  1. Disable local echo, so your program handles every local keypress before it's rendered by the caret in the terminal.
  2. Your local keypress handling code will need to be asynchronous so it doesn't block on getchar while waiting for the user to enter the next character of their message or [Enter].
    • This is important so that your program can still run to collect and display messages received on the network end. While you could use a second thread for this it would mean two threads would be using stdio at the same time which is inadvisable, while you could use thread synchronization primitives to prevent this bug you're better-off using an asynchronous IO API instead.
    • Important note: "asynchronous" code does not mean "concurrent" nor does it imply the use of threading. In practice, it means the program's thread will return to a central dispatcher (cooperative yielding) instead of blocking on IO and the dispatcher will resume the function where it yielded when the IO operation completes (this is what the await keyword does in C# and JavaScript).
    • However, in C, working with the asynchronous terminal/console API in Linux is a PITA and you're better off using a library like ncurses which handles this for you.
  3. When your program receives a message to display, you would clear the bottom line of the window (by overwriting it with whitespace or using VT100 ^[[2K), write the received message, then re-write the user's incomplete entered input (if any) on a new line.
  4. Repeat.

Upvotes: 1

Related Questions