Home > OS >  Is it possible to get input live from fgets() in C?
Is it possible to get input live from fgets() in C?

Time:04-25

Apologies if this is unclear, but I'm really not sure how to describe this.

See, my issue is that I'm trying to read from the text for user input using fgets(), however, I also need to know if the user presses a special key like /b (backspace) since ideally I want it to start deleting characters from the line before if the current line is empty, like a text editor, which isn't possible with C.

Anyways, let me know if you need more information, thanks in advance.

EDIT: Thought I'd go ahead and post what I have as of now in case someone comes across this later with the same issue to get a better idea

for (; ;) 
 {  
  int i; 
  int key = getch();
  
  if (key == '/b')
  {  
   printf("Hello World");
  }  

  else
  {  
   buffer[i  ] = key; // adding character to text user is writing
  }  
  i  ;
 }

note that this code doesn't work at the moment because of a linker error and something with the /b, but in essence, this could work.

EDIT 2: Thank you chqrlie for bringing up the right way to refer to special characters. Forgot you had to use the backslash for them.

CodePudding user response:

You can certainly write text editors in C :-) A lot of them are.

However, you can't write them in portable C because the facilities required for interactive character-by-character terminal I/O don't exist in standard C. They don't exist because standard C doesn't assume that there is such a thing as a terminal (lots of embedded CPUs don't have any such thing, for example), and it would go far beyond the mandate of ISO C to try to standardise the disparate communications protocols of the various operating systems which do have terminal-like I/O.

getch is an obsolete interface in the Windows conio.h header, and also one of the interfaces in the Curses library, which is available for many operating systems (including Windows). It has nothing to do with fgets, which is part of standard C, and it cannot be implemented using fgets.

It seems likely that what you are trying to do could best be accomplished using an implementation of Curses. (If you're using Linux, as suggested by your avatar, you would be looking for Ncurses.) You might want to look at the Forms library built on top of Ncurses, which provides higher-level input facilities, like editable text boxes.

Another common input-handling library, GNU readline, might also be useful, but it doesn't handle multiline input forms so it would probably be a lot more work.

  • Related