Continuous input in C....

Status
Not open for further replies.
Hello all,

I was wondering if there is a way to read in the newline in C and carry on reading until something like Ctrl-C is hit, i.e.,

>> Please enter input: so far so good scanf or fgets will do this <CR>
but now I have hit enter and still want this to be read in <LF>
Now a line feed has been entered...still want to read this <Ctrl-C>

NOW stop reading...so if I have declared char input[400];
I should have the entire input from So far....to read this. Thanks very much

Regards,
Hellfire
:D Constantly working on "it" :D
 
Looks like anything inside angled brackets is getting eaten by Mozilla, dunno about other browsers, so here's clarification.

>> Please enter input: so far so good scanf or fgets will do this <CR>
....At this point I hit ENTER
but now I have hit enter and still want this to be read in <LF>
...At this point I somehow entered LINE FEED.
Now a line feed has been entered...still want to read this <Ctrl-C>
...Atthis point I hit Ctrl-C to stop....

thx again
 

angst

Smack-Fu Master, in training
51
1. you don't want Ctrl^C to be your control termincator since by default on xterms ( unless you have some funky xdefaults merged in ) this sequence sends interrupt signal to the foreground process , in which case you'd have to catch it, spin your input loop controlling variable and keep going. On top of that chances are that the signal was cought from the read/fgetc/etc system call, so once the handler returns you'll have to supply an extra character before the loop breaks. Obviously there are ways around that, but overall it's too messy for a simple job such as yours, so ....

2. use Ctrl^D as your escape sequence. Ctrl^D sends a EOT ( end of transmission ) character to the terminal ( this is not a signal, btw ), for which you can test to see if the input loop should continue. Finally, you'll have to disable cannonical mode for the terminal, anyway here's an example ( i even commented the code! )


Code:
#include <stdio.h>
#include <unistd.h>
#include <termios.h>

int main( )
{
  const int BUF_SIZE = 512, EOT = 4; /* buffer size, ASCII End of Transmision def */
  char buf[BUF_SIZE],       c = 0;   /* buffer, controlling input character */
  struct termios term_settings;      /* terminal settings */
  int cc = 0;                        /* character counter */
  
  /* disable cannonical (line) input */
  tcgetattr(STDIN_FILENO, &term_settings);
  term_settings.c_lflag &= ~ICANON;
  tcsetattr(STDIN_FILENO, TCSANOW, &term_settings); 

  /* read from standard input until buffer is full ( reserver space for terminator ) or EOT is encountered */
  while((c = fgetc(stdin)) != EOT && cc < BUF_SIZE-1)
    buf[cc++] = c;
  buf[cc] = 0;
  return 0;
}
 
Status
Not open for further replies.