简体   繁体   中英

How to write to input part in C?

I'm trying to write a mini shell in C for a school project, and what I want to do is doing a sort of command history (like in shell), when I press the UP key it writes the previous input into the input part, DOWN does the opposite, etc..., and you can edit it before pressing enter to send it to the program, like this (sorry for the bad english): [] represents the user cursor

my_shell$ some input wrote by me
my_shell$ []
my_shell$ some other input
my_shell$ []
and now if I press UP
my_shell$ some other input[]
If I press UP again
my_shell$ some input wrote by me[]

I'm allowed to use termcaps and some other functions isatty, ttyname, ttyslot, ioctl, getenv, tcsetattr, tcgetattr, tgetent, tgetflag, tgetnum, tgetstr, tgoto, tputs .

The problem is I can't understand the documentation of ioctl and tty functions, and I can't find well explained tutorials on these functions with examples, and I can't find the documentation for what I'm trying to do with them.

Can someone explain me those functions in an understandable way? And how should I apply them for what I'm trying to do (I'm searching for a Linux-MacOs compatibility way) Thanks for your help.

What you are asking is non trivial and will require a fair amount of work. Basically, what you need to do is use tcsetattr to put the terminal into non-canonical mode where the terminal's input line buffering is disabled and every keystroke will be returned immediately rather than waiting for a newline. You will then have to process every keystroke yourself, including backspace/delete and up/down arrows. Because of what you want to do with line editing, you'll probably also have to disable echoing and do the echo yourself.

You'll need to maintain the current line buffer yourself, and you'll also need a data structure that stores all the older lines of input (the history) and when an up-arrow is hit, you'll need to erase what you've currently buffered for the input, and erase it from the screen, then copy the history into your current buffer and echo it to the terminal.

Another complication is that keys like up-arraow and down-arrow are not part of ascii, so won't be read as a single byte -- instead they'll be multibyte escape sequences (likely beginning with an ESC ( '\x1b' ) character). You can use tgetstr to quesry the terminal database to figure out what they are, or just hardcode your shell to use the ANSI sequences which are what almost all terminals you will see these days use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM