I know there are many similar questions, but I could not find answers clear enough.
I am writing something that resembles a little primitive shell in C. I am constantly querying the user to enter commands, which I process. To read a line, I use fgets()
. It works really nice (I have to remove the \n
every time though), but if I want to move the cursor when typing something, the raw key codes get put into the console instead. Not only can I not use the up and down arrow keys to get previous commands, I am also unable to correct any typos without deleting everything with backspace until the typo and then typing stuff back again.
The same happens when using scanf()
, so fgets()
is not the culprit. Interestingly enough, it works just fine when I'm trying on Windows. Also, as I said, for example the backspace key actually deletes characters…
I know I could use ncurses
, but I would rather find another elegant solution…
You need a library like readline
.
Don’t get entangled in ‘portable code.’
You can use Conditional Inclusion
to stay compatible on different platforms.